你可以通过两种方法执行此操作,或者通过从
read或
readline函数创建迭代器,然后执行以下操作:
import subprocessimport syswith open('test.log', 'w') as f: # replace 'w' with 'wb' for Python 3 process = subprocess.Popen(your_command, stdout=subprocess.PIPE) for c in iter(lambda: process.stdout.read(1), ''): # replace '' with b'' for Python 3 sys.stdout.write(c) f.write(c)要么
import subprocessimport syswith open('test.log', 'w') as f: # replace 'w' with 'wb' for Python 3 process = subprocess.Popen(your_command, stdout=subprocess.PIPE) for line in iter(process.stdout.readline, ''): # replace '' with b'' for Python 3 sys.stdout.write(line) f.write(line)或者,你可以创建
reader和
writer文件。将传递
writer到
Popen并从中读取
reader
import ioimport timeimport subprocessimport sysfilename = 'test.log'with io.open(filename, 'wb') as writer, io.open(filename, 'rb', 1) as reader: process = subprocess.Popen(command, stdout=writer) while process.poll() is None: sys.stdout.write(reader.read()) time.sleep(0.5) # Read the remaining sys.stdout.write(reader.read())
这样,你就可以将数据写入
test.log和标准输出中。
文件方法的唯一优点是你的代码不会被阻塞。因此,你可以同时做任何你想做的事,并reader以不阻塞的方式随时阅读。当使用
PIPE,read和
readline功能将阻塞,直到任一个字符被写入到管或线被分别写入到管道。



