Possible Duplicate:
Assignment Condition in Python While Loop
这相当于什么:
while (line = p.stdout.readline()) != '':
...
在 Python 中?
我不喜欢这样做:
line = p.stdout.readline()
while line != '':
sys.stdout.write(line)
line = p.stdout.readline()
虽然我多年来一直在使用后者……但我怀疑没有其他选择。我以为 p.stdout
支持迭代,比如
for line in p.stdout:
sys.stdout.write(line)
但不幸的是,它不像从 open()
返回的句柄那样。
编辑: 抱歉,我错了,它确实支持它,问题是我无法像使用 p.stdout.readline() 那样立即将其取出
。添加 sys.stdout.flush()
似乎没有帮助,因此它必须在 p.stdout
中进行缓冲。
您可以使用内置函数 iter()
完成此操作使用双参数调用方法:
for line in iter(p.stdout.readline, ''):
...
相关文档:
iter(o[, sentinel])
...
If the second argument, sentinel, is given, then o must be a callable object. The iterator created in this case will call o with no arguments for each call to its next()
method; if the value returned is equal to sentinel, StopIteration
will be raised, otherwise the value will be returned.
One useful application of the second form of iter()
is to read lines of a file until a certain line is reached. The following example reads a file until the readline()
method returns an empty string:
with open('mydata.txt') as fp:
for line in iter(fp.readline, ''):
process_line(line)
编辑:根据您的编辑,您的实际问题似乎与缓冲有关。根据上下文,我猜您正在使用 subprocess.Popen()
和 stdout=subprocess.PIPE
。而不是直接使用文件句柄 p.stdout
你应该是 p.communicate()
读取子进程的输出。