Keep a subprocess alive and keep giving it commands? Python(保持子进程活着并继续给它命令?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一个>模块.您使用 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
')
process.stdin.flush()
print(repr(process.stdout.readline())) # Should print 'Hello
'
process.stdin.write(b'World
')
process.stdin.flush()
print(repr(process.stdout.readline())) # Should print 'World
'
# "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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:保持子进程活着并继续给它命令?Python


基础教程推荐
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 包装空间模型 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01