p = subprocess.Popen(..., stderr=subprocess.PIPE)
fd = p.stderr.fileno()
my_stderr = os.fdopen(os.dup(fd), 'rU', new_bufsize)
os.close(fd)
# use my_stderr from here on
如果您最终打算将 stdout
/stderr
写入文件,并且只需要输出不缓冲,那么可以使用以下方法:
LOG_FILE = codecs.open('somelog.txt', 'a', 'utf_8', buffering=0)
subprocess.Popen(ARGS, stdout = LOG_FILE, stderr = LOG_FILE).communicate()
那么使用的缓冲区将是文件的缓冲区,在这种情况下:没有缓冲。
out = subprocess.Popen(['ls'], stdout=subprocess.PIPE, bufsize=0)
,然后,cat = subprocess.Popen(['ls'], stdin=out.stdout, stderr=subprocess.PIPE, bufsize=1)
。在第一个例子中,stdout
是无缓冲的,而具有相同参数的stderr
是行缓冲的。 - user225312