开发者

How do I create a subprocess in Python?

I would like to create a开发者_JS百科 subprocess of a process.

What would be a working example which shows how to accomplish this?


Start with the subprocess documentation.

If you want to get the output:

>>> import subprocess
>>> output = subprocess.Popen(['uname', '-a'], stdout=subprocess.PIPE).communicate()[0]
>>> output
'Linux'

If you just want to call and not deal with the output:

>>> subprocess.call(['echo', 'Hi'])
Hi
0

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.


Launching and monitoring a subprocess:

import subprocess, time, os, signal
args=['/usr/bin/vmstat','-n','2']
app=subprocess.Popen(args=args, stdout=open('somefile','w'))
print "Your app's PID is %s. You can now process data..." % app.pid
time.sleep(5)
if app.poll() == None: print "Process is still running after 5s."
print "The app outputed %s bytes." % len(open('somefile','r').read())
print "Stopping the process..."
os.kill(app.pid, signal.SIGTERM)

There is more to it. Just check the Popen docs.


import subprocess

subprocess.call(['echo', 'hello world'])


This is what worked for me if you want to run a simple command instead of giving a seperate file

import subprocess
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
process.wait()
print process.returncode

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 than 0 then you can check here what that error code means: http://tldp.org/LDP/abs/html/exitcodes.html

For more details about Subprocess: http://docs.python.org/library/subprocess.html


if os.name == 'nt':
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess._subprocess.STARTF_USESHOWWINDOW
subprocess.call(os.popen(tempFileName), shell=True)
os.remove(tempFileName)


Based on user225312's answer, I prepared the below one liner, it may help you to test the subprocess:

python -c "import subprocess;
output = subprocess.Popen(['uname', '-a'], stdout=subprocess.PIPE).communicate()[0]; 
print output"

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜