【问题标题】:Within contextlib.redirect_stdout() the print()-function causes an AttributeError: 'str' object has no attribute 'write'在 contextlib.redirect_stdout() 中, print() 函数会导致 AttributeError: 'str' object has no attribute 'write'
【发布时间】: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


【解决方案1】:

我通过将 file-handler "f" 传递给函数 contextlib.redirect_stdout(f) 而不是文件路径 dummy_file 找到了解决方案,如建议in this post

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)

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

【讨论】:

  • 我正要发表评论,暗示您很可能传递的是文件名(字符串)而不是文件对象 xD
  • 哈哈哈,好吧,幸好我跑得更快 :D
猜你喜欢
  • 2020-04-26
  • 1970-01-01
  • 2017-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-09
  • 2020-12-29
  • 1970-01-01
相关资源
最近更新 更多