使用标准子流程模块。您使用subprocess.Popen()启动该过程,该过程将在后台运行(即与Python程序同时运行)。调用Popen()时,您可能希望将stdin,stdout和stderr参数设置为subprocess.PIPE。然后,您可以使用返回对象上的stdin,stdout和stderr字段来写入和读取数据。
未经测试的示例代码:
from subprocess import Popen, PIPE# Run "cat", which is a simple Linux program that prints it's input.process = Popen(['/bin/cat'], stdin=PIPE, stdout=PIPE)process.stdin.write(b'Hellon')process.stdin.flush()print(repr(process.stdout.readline())) # Should print 'Hellon'process.stdin.write(b'Worldn')process.stdin.flush() print(repr(process.stdout.readline())) # Should print 'Worldn'# "cat" will exit when you close stdin. (Not all programs do this!)process.stdin.close()print('Waiting for cat to exit')process.wait()print('cat finished with return pre %d' % process.returnpre)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)