使子进程保持活动状态并继续向其发送命令? Python [英] Keep a subprocess alive and keep giving it commands? Python

查看:91
本文介绍了使子进程保持活动状态并继续向其发送命令? Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用给定的命令在python中生成一个新的subprocess(假设我使用python命令启动python解释器),如何将新数据(通过STDIN)发送到进程?

If I spawn a new subprocess in python with a given command (let's say I start the python interpreter with the python command), how can I send new data to the process (via STDIN)?

推荐答案

使用标准的子流程模块.您使用subprocess.Popen()启动该过程,该过程将在后台运行(即与您的Python程序同时运行).调用Popen()时,您可能希望将stdin,stdout和stderr参数设置为subprocess.PIPE.然后,您可以使用返回的对象上的stdin,stdout和stderr字段来写入和读取数据.

Use the standard subprocess module. You use subprocess.Popen() to start the process, and it will run in the background (i.e. at the same time as your Python program). When you call Popen(), you probably want to set the stdin, stdout and stderr parameters to subprocess.PIPE. Then you can use the stdin, stdout and stderr fields on the returned object to write and read data.

未经测试的示例代码:

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'Hello\n')
process.stdin.flush()
print(repr(process.stdout.readline())) # Should print 'Hello\n'
process.stdin.write(b'World\n')
process.stdin.flush()  
print(repr(process.stdout.readline())) # Should print 'World\n'

# "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 code %d' % process.returncode)

这篇关于使子进程保持活动状态并继续向其发送命令? Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆