您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

使子进程保持活动状态并继续向其发送命令?python

使子进程保持活动状态并继续向其发送命令?python

使用标准子流程模块。您使用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'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 2022/1/1 18:33:29 有513人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶