Python 在contextlib.redirect_stdout()中,print()函数导致AttributeError:';str';对象没有属性';写';

Python 在contextlib.redirect_stdout()中,print()函数导致AttributeError:';str';对象没有属性';写';,python,python-3.x,printing,writetofile,console-output,Python,Python 3.x,Printing,Writetofile,Console Output,我尝试按照的建议将python代码特定部分的整个控制台输出重定向到文本文件 根据那篇文章,它应该与contextlib.redirect\u stdout()一起工作,但是当第一个print()-命令出现在我的自定义函数custom\u function\u中,并带有内部的\u print\u calls(),它抛出AttributeError:'str'对象没有属性'write' 编辑: 在我的特殊情况下,我使用的不是with环境中的print()-函数,而是一个自定义函数,该函数具有对Pyt

我尝试按照的建议将python代码特定部分的整个控制台输出重定向到文本文件

根据那篇文章,它应该与contextlib.redirect\u stdout()一起工作,但是当第一个print()-命令出现在我的自定义函数custom\u function\u中,并带有内部的\u print\u calls(),它抛出AttributeError:'str'对象没有属性'write'

编辑: 在我的特殊情况下,我使用的不是with环境中的print()-函数,而是一个自定义函数,该函数具有对Python内置print()函数的内部调用。print()-函数是否出现在另一个函数中,或者是否直接出现在顶层以重现错误,这应该无关紧要

已尝试的选项: 其他变通方法似乎无法提供我正在寻找的解决方案,例如

(因为我使用的是python 3.7x), 或者也

通过
打印('Filename:',Filename,file=f)
。 在我的例子中,后者意味着将一个文件处理程序传递给我选择的封闭函数中的所有子函数,这对于这种特殊情况来说是太多额外的代码修改

我希望能够使用contextlib.redirect_stdout(dummy_文件)的环境
围绕我的函数,以便将这个函数的每个控制台输出重定向到dummy_文件

这也帮不了我。
提前感谢您的建议。

我通过向函数
contextlib传递一个文件处理程序“f”找到了解决方案。重定向stdout(f)
而不是建议的文件路径伪文件


这样,所有print()-函数调用都会写入伪_文件,并在之后恢复标准控制台输出。

发布您的全部代码。发布的代码不包含对名为
write
的属性的引用,因此我不知道我们能提供什么帮助。请发布正确的(而不是“您的全部代码”)-只有重现问题所需的最少代码。)@JohnGordon我想我们可以假设
print\u out\u all\u TIFF\u Tags\u n\u filter\u for\u required\u Tags
包含
sys.stdout.write()
print()
调用(后者主要是第一个调用的包装器)。我刚刚编辑了我的帖子。确切地说,print()-函数会导致错误,显然在哪个嵌套级别调用它并不重要(在我的自定义函数中)。不管怎样,我已经解决了这个问题,从下面的回答中可以看出。我必须向contextlib.redirect_stdout()-函数传递一个文件处理程序而不是文件路径。我正要发布一条评论,建议您很可能传递的是一个文件名(字符串),而不是文件对象xDHahaha,幸运的是我传递得更快:D
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)
dummy_file = "dummy_textfile.txt"  # file to which the stdout shall be redirected

with open(dummy_file, 'w') as f:
    with contextlib.redirect_stdout(f):
        # Indirect print()-function calls (internally)
        custom_function_with_internal_print_calls(**kwargs)