我总是使用with语句打开并写入文件:

with open('file_path', 'w') as handle:
    print >>handle, my_stuff

但是,在一种情况下,我需要变得更加灵活,并写入sys.stdout(或其他类型的流)(如果提供了它而不是文件路径):

所以,我的问题是:有没有办法在实际文件和with中同时使用sys.stdout语句?

请注意,我可以使用以下代码,但是我认为这违背了使用with的目的:
if file_path != None:
    outputHandle = open(file_path, 'w')
else:
    outputHandle = sys.stdout

with outputHandle as handle:
    print >>handle, my_stuff

最佳答案

您可以创建一个上下文管理器并像这样使用它

import contextlib, sys

@contextlib.contextmanager
def file_writer(file_name = None):
    # Create writer object based on file_name
    writer = open("Output.txt", "w") if file_name is not None else sys.stdout
    # yield the writer object for the actual use
    yield writer
    # If it is file, then close the writer object
    if file_name != None: writer.close()

with file_writer("Output.txt") as output:
    print >>output, "Welcome"

with file_writer() as output:
    print >>output, "Welcome"

如果您没有将任何输入传递给file_writer,它将使用sys.stdout

10-06 09:07
查看更多