gpt4 book ai didi

python - 使用带有 sys.stdout 的 Python 'with' 语句

转载 作者:太空狗 更新时间:2023-10-29 21:37:23 25 4
gpt4 key购买 nike

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

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

但是,在一个实例中,我需要能够更加灵活,并写入 sys.stdout(或其他类型的流),如果提供了 而不是 文件路径:

所以,我的问题是:有没有办法对真实文件和 sys.stdout 使用 with 语句?

请注意,我可以使用以下代码,但我认为这违背了使用 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(file_name, "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

关于python - 使用带有 sys.stdout 的 Python 'with' 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22264504/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com