【发布时间】:2020-01-15 17:41:55
【问题描述】:
我尝试按照this post 的建议将我的python 代码的特定部分的整个控制台输出重定向到一个文本文件。
根据那篇文章,它应该与 contextlib.redirect_stdout() 一起使用,但是当第一个 print() 命令出现在我的自定义函数 custom_function_with_internal_print_calls() 中时,它会抛出 AttributeError : 'str' 对象没有属性 'write'.
dummy_file = "dummy_textfile.txt" # file to which the stdout shall be redirected
with contextlib.redirect_stdout(dummy_file):
# Direct print()-function call
print("Informative string which shall go to the textfile instead of the console.")
# Indirect print()-function calls (internally)
custom_function_with_internal_print_calls(**kwargs)
编辑: 在我的特定情况下,我有一个自定义函数,而不是 with 环境中的 print() 函数,它具有对 Python 内置 print() 函数的内部调用。如果 print() 函数出现在另一个函数中,或者直接出现在顶层以重现错误,这无关紧要。
已经尝试过的选项: 其他解决方法似乎无法提供我正在寻找的解决方案,例如
redefining the print()-function 或
writing a decorator for python 2.7x(因为我使用的是 python 3.7x), 或者也
redirecting the print()-function to a file object 通过print('Filename:', filename, file=f)。
在我的情况下,后者意味着将文件处理程序传递给我选择的封闭函数中的所有子函数,对于这种特殊情况,这需要太多额外的代码修改。
我希望能够只使用环绕我的函数的环境with contextlib.redirect_stdout(dummy_file):,以便将这个函数的每个控制台输出重定向到 dummy_file。
documentation of contextlib.redirect_stdout() 也对我没有帮助。 提前感谢您的建议。
【问题讨论】:
-
发布您的整个代码。
-
发布的代码不包含对名为
write的属性的引用,所以我不知道我们能提供什么帮助。 -
请发布正确的minimal reproducible example(不是“您的全部代码”——仅是重现问题所需的最少代码)。
-
@JohnGordon 我想我们可以假设
print_out_all_TIFF_Tags_n_filter_for_desired_TAGs包含sys.stdout.write()或print()调用(后者主要是第一个的包装)。 -
我刚刚编辑了我的帖子。确切地说, print() 函数会导致错误,并且显然在哪个嵌套级别调用它并不重要(在我的自定义函数中)。无论如何,我已经解决了这个问题,如下面的回答所示。我必须将文件处理程序而不是文件路径传递给 contextlib.redirect_stdout() - 函数。
标签: python python-3.x printing writetofile console-output