python中的无缓冲stdout(如python-u中所示)来自程序内部

2024-06-25 07:21:11 发布

您现在位置:Python中文网/ 问答频道 /正文

Possible Duplicate:
Python output buffering

有没有办法从我的代码中获得运行python-u的效果?如果失败,我的程序可以检查它是否在-u模式下运行,如果不是,则退出并显示错误消息吗?这是在linux上(Ubuntu8.10服务器)


Tags: 代码程序服务器消息outputlinux错误模式
3条回答

我能想到的最好的:

>>> import os
>>> import sys
>>> unbuffered = os.fdopen(sys.stdout.fileno(), 'w', 0)
>>> unbuffered.write('test')
test>>> 
>>> sys.stdout = unbuffered
>>> print 'test'
test

在GNU/Linux上测试。它似乎也应该在窗户上工作。如果我知道如何重新打开sys.stdout,会容易得多:

sys.stdout = open('???', 'w', 0)

参考文献:
http://docs.python.org/library/stdtypes.html#file-objects
http://docs.python.org/library/functions.html#open
http://docs.python.org/library/os.html#file-object-creation

[编辑]

请注意,在覆盖sys.stdout之前最好先关闭它。

您始终可以在shebang行中传递-u参数:

#!/usr/bin/python -u

假设你在Windows上:

msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)

。。。在Unix上:

fl = fcntl.fcntl(sys.stdout.fileno(), fcntl.F_GETFL)
fl |= os.O_SYNC
fcntl.fcntl(sys.stdout.fileno(), fcntl.F_SETFL, fl)

(Unix从注释的解决方案复制进来,而不是链接。)

相关问题 更多 >