我正在编写一个脚本,我有一个选项,可以在命令行上传递,脚本是否应该将其结果打印到标准输出或预定义的结果文件。代码大纲如下所示。我现在已经阅读了一些关于 Python 中的上下文管理器的内容,但我不确定在这种特定情况下是否以及如何使用上下文管理器。所以我正在寻求建议
- 在这个问题中使用上下文管理器是否有意义
- 如何着手实施它。
因此,没有上下文管理器的代码是:
option_file = True # would come from OptionParser in real code
if option_file:
out = open("resultsfile", "w")
else:
out = sys.stdout
# do some computations
out.write("Results of script")
# more computations and calls to out.write
if option_file:
out.close()