我需要在使用构建构建的脚本中使用无缓冲的输出。
我的方法是指定-u
生成的脚本中的 Python 标志。
这是我的 buildout.cfg:
[buildout]
parts = python
develop = .
[python]
recipe = zc.recipe.egg:scripts
eggs = myproject
和setup.py:
from setuptools import setup, find_packages
setup(
name = 'myproject',
packages = find_packages(),
entry_points = """
[console_scripts]
myscript = myproject:main
""",
)
我得到以下配置的 shebang:
$ pip install .
$ head -n1 /usr/local/bin/myscript
#!/usr/bin/python
我想要这个:
#!/usr/bin/python -u
怎么做?我尝试添加arguments = -u
and interpreter = python -u
to buildout.cfg
。它不起作用。
您可以通过在文件号上打开一个新文件对象来重新打开 stdin 或 stdout,从而在 Python 脚本中强制使用无缓冲 I/O:
import io, os, sys
try:
# Python 3, open as binary, then wrap in a TextIOWrapper
unbuffered = io.TextIOWrapper(open(sys.stdout.fileno(), 'wb', 0), write_through=True)
except TypeError:
# Python 2
unbuffered = os.fdopen(sys.stdout.fileno(), 'w', 0)
如果您想使用使用 stdout 或 stdin 的其他模块或内置程序,则可以重新分配 sys.stdout:
sys.stdout = unbuffered
另请参阅来自程序内部的 python 中的无缓冲标准输出(如 python -u 中)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)