4

我需要在使用 buildout 构建的脚本中使用无缓冲输出。

我的方法是-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 = -uinterpreter = python -ubuildout.cfg. 它没有用。

4

1 回答 1

3

您可以通过在文件编号上打开一个新文件对象来重新打开标准输入或标准输出,从而在 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 中)

于 2011-03-26T16:59:08.060 回答