我正在使用子流程运行脚本,在管道上获取脚本的输出并在输出上获取进程。从Popen文件对象中完全读取内容
我遇到了一个奇怪的问题,有时候它会读到脚本结束,而有时候它会一直读到最后。
我怀疑这可能是与缓冲区大小的问题..试过一些办法,但都没有成功的还..
def main():
x = subprocess.Popen('./autotest', bufsize = 1, stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE, cwd = '/home/vijay/run/bin', shell = True)
with open("out.txt",'wb') as f:
for line in x.stdout:
if 'Press \'q\' to quit scheduler' in line:
print line.strip()
f.write(line.strip())
x.stdin.write('q')
f.write('\n')
x.stdin.close()
x.stdout.flush()
try:
x.stdout.read()
except:
print 'Exception Occured !!!'
os._exit(1)
else:
print line.strip()
f.write(line.strip())
f.write('\n')
x.stdout.flush()
if __name__ == '__main__':
main()
你为什么要flush()''x.stdout'? – Amber 2012-07-05 17:29:37
您是否尝试过使用沟通?此外,它似乎并不像你甚至使用stderr PIPE – jdi 2012-07-05 17:32:21
@Amber我用flush()只是为了看看要读取的内容是否在缓冲区中。但实际上并没有帮助 – user596922 2012-07-05 17:35:09