我正在使用 subprocess 来运行脚本,在管道上获取脚本的输出并在输出上进行处理。
我遇到了一个奇怪的问题,有时它会读到脚本的结尾,而有时它不会读到最后。
我怀疑这可能是缓冲区大小的问题..尝试了一些替代方案,但尚未成功..
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()