从命令行-u选项的二进制文件中的Python管道

时间:2011-09-30 06:44:52

标签: python

是否存在一个传递二进制文件的解耦方法,而不会在运行程序的整个持续时间内遇到python有无缓冲stdout的惩罚(如果我打算只使用cmdline而不打开(...,'rb') )?似乎-u是将文件作为二进制数据读取的唯一方法(来自cmdline)

http://docs.python.org/using/cmdline.html

-u强制stdin,stdout和stderr完全无缓冲。在重要的系统上,还将stdin,stdout和stderr置于二进制模式。

2 个答案:

答案 0 :(得分:1)

您可以通过从sys.stdin类文件对象中取出fileno并使用os.read()从中获取数据来避免Python的文件模式?

import os
import sys

stdin_no = sys.stdin.fileno()
some_bytes = os.read(stdin_no, 1024)

答案 1 :(得分:0)

此代码将标准输入(仅)更改为无缓冲模式。使用此方法,您无需使用-u调用解释器。仅限Unix。

import fcntl, os, sys

def set_fd_nonblocking(fd):
  u"put an open file descriptor into non-blocking I/O mode"
  if fcntl.fcntl(fd, fcntl.F_SETFL, os.O_NONBLOCK) != 0:
    raise IOError, "can't set file descriptor %s option O_NONBLOCK" % (fd,)

set_fd_nonblocking(sys.stdin.fileno())

但是我不确定这会产生什么副作用,例如raw_input内置函数。

小心;即使在非阻止模式下,如果select告诉您fd已准备好阅读,您仍需要抓住OSError并检查e.errno == os.errno.EAGAIN。应该忽略这些错误。