How do I create a subprocess in Python?

2019-02-23 23:46发布

问题:

I would like to create a subprocess of a process.

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

回答1:

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.



回答2:

import subprocess

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


回答3:

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.



回答4:

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



回答5:

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