如何在 Python 中创建子进程?
我想创建一个流程的子流程。
展示如何实现这一目标的工作示例是什么?
I would like to create a subprocess of a process.
What would be a working example which shows how to accomplish this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
从 subprocess 文档开始。
如果你想获得输出:
如果你只想调用而不处理输出:
subprocess.check_call 是相同的,只是它会在使用无效参数调用命令时抛出
CalledProcessError
。很好的子流程教程。
Start with the subprocess documentation.
If you want to get the output:
If you just want to call and not deal with the output:
subprocess.check_call is the same except that it throws up a
CalledProcessError
in case the command is called with invalid parameters.A good subprocess tutorial.
启动和监视子流程:
还有更多内容。只需检查 Popen 文档即可。
Launching and monitoring a subprocess:
There is more to it. Just check the Popen docs.
如果您想运行一个简单的命令而不是提供一个单独的文件,这对我有用。
要获取进程的返回码,您可以使用
process.returncode
要获得响应,您可以使用
process.communicate()
,以防万一您感到困惑,
如果您收到
, 您可以使用
除了command="ls"
来测试此代码>returncode0
之外,那么您可以在此处检查该错误代码的含义:http://tldp.org/LDP/abs/html/exitcodes.html有关子进程的更多详细信息:http://docs.python.org/library/subprocess.html
This is what worked for me if you want to run a simple command instead of giving a seperate file
To get returncode of process you can use
process.returncode
To get response you can use
process.communicate()
in case if you are confuse you can just test this code by using
command="ls"
if you are getting
returncode
other than0
then you can check here what that error code means: http://tldp.org/LDP/abs/html/exitcodes.htmlFor more details about Subprocess: http://docs.python.org/library/subprocess.html
根据user225312的回答,我准备了下面的一个衬垫,它可以帮助您测试子进程:
结果如下:
Linux xxx.xxx.xxx.xxx 3.10.0-957.1.3.el7.x86_64 #1 SMP 11 月 29 日星期四 14:49:43 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux
Based on user225312's answer, I prepared the below one liner, it may help you to test the subprocess:
result like:
Linux xxx.xxx.xxx.xxx 3.10.0-957.1.3.el7.x86_64 #1 SMP Thu Nov 29 14:49:43 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux