来自程序内的 python 中的无缓冲标准输出(如在 python -u 中) [英] unbuffered stdout in python (as in python -u) from within the program

查看:45
本文介绍了来自程序内的 python 中的无缓冲标准输出(如在 python -u 中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<块引用>

可能的重复:
Python 输出缓冲

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

解决方案

我能想到的最好的:

<预><代码>>>>导入操作系统>>>导入系统>>>无缓冲 = os.fdopen(sys.stdout.fileno(), 'w', 0)>>>unbuffered.write('test')测试>>>>>>sys.stdout = 无缓冲>>>打印测试"测试

在 GNU/Linux 上测试.似乎它也应该适用于 Windows.如果我知道如何重新打开 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-对象创建

请注意,在覆盖之前关闭 sys.stdout 可能会更好.

Possible Duplicate:
Python output buffering

Is there any way to get the effect of running python -u from within my code? Failing that, can my program check if it is running in -u mode and exit with an error message if not? This is on linux (ubuntu 8.10 server)

解决方案

The best I could come up with:

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

Tested on GNU/Linux. It seems it should work on Windows too. If I knew how to reopen sys.stdout, it would be much easier:

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

References:
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

[Edit]

Note that it would be probably better to close sys.stdout before overwriting it.

这篇关于来自程序内的 python 中的无缓冲标准输出(如在 python -u 中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆