简体   繁体   English

“ contextlib.redirect_stdout”不适用于Ipython

[英]“contextlib.redirect_stdout” not working on Ipython

I am working on Ipython like to get help info about os.stat and redirect the output to a plain markdown file: 我正在Ipython上工作,希望获得有关os.stat帮助信息,并将输出重定向到普通的markdown文件:

In [57]: with contextlib.redirect_stdout(open("stat_help_docs.md", "w")):
    ...:     help(os.stat)
    ...:     
In [58]: os.stat("stat_help_docs.md").st_size
Out[58]: 1

The "stat_help_docs.md" is empty, it failed to write help docs to it. “ stat_help_docs.md”为空,无法向其中写入帮助文档。
However, If I tried in the Standard Python Interactive Mode: 但是,如果我在标准Python交互模式下尝试过:

>>> import os
>>> import contextlib
>>> with contextlib.redirect_stdout(open("another_stat_help_docs.md", "w")):
...     help(os.stat)
... 
>>> os.stat("another_stat_help_docs.md").st_size
919

It succeeded in write to the file. 它已成功写入文件。
I assume the problem might lie in the setting of Ipython, 我认为问题可能出在Ipython的设置上,
Could please provide any hints to help dig in the problem? 请提供任何提示来帮助您解决问题?

You need flush the file write buffer: 您需要刷新文件写缓冲区:

In [9]: f = open('stat_help_docs.txt', 'w')


In [10]: with contextlib.redirect_stdout(f):
    ...:     help(os.stat)

In [11]: os.stat("stat_help_docs.txt").st_size
Out[11]: 0

In [12]: f.flush()

In [13]: os.stat("stat_help_docs.txt").st_size
Out[13]: 919

In the standard python shell, the file object gets recycled right after with context and the underlying write buffer is flushed, no idea why IPython shell holds extra references for the file object. 在标准的python shell中,文件对象在上下文之后立即回收with并且刷新了底层的写缓冲区,不知道为什么IPython shell会为文件对象保留额外的引用。

But IMO one shouldn't rely on GC to flush the write buffer, either use file obj as a context manager ( with open('...'): ) or flush explicitly. 但是,IMO不应依赖GC刷新写入缓冲区,而应将文件obj用作上下文管理器( with open('...'): :)或显式刷新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM