This module is used for dealing with external commands, intended to be a replacement to the old
os.system
and the like.
The subprocess module allows us to spawn processes, connect to their input/output/error pipes, and obtain their return codes
subprocess.call()
shell is set to flase default
import subprocess
ls_output = subprocess.check_output(['ls'])
subprocess.check_output(['ls', '-l'])
Subprocess can also run command-line instructions via a shell program.
This is usually dash/bash on Linux and cmd on windows.
subprocess.call('ls | wc -l', shell=True)
Input and Output
Return Codes
You can use subprocess.call return codes to determine the success of the command.
Every process will return an exit code and you can do something with your script
based on that code.
If the return code is anything else than zero, it means that an error occurred.
stdin, stdout and stderr
One of the trickiest part I had with subprocess was how to work with pipes
and to pipe commands together.
PIPE indicates that a new pipe to the child should be created.
The default setting is "None", which means that no redirection will occur.
The standard error (or stderr) can be STDOUT, which indicates that the stderr data from the child process should be captured into the same file handle as for stdout.
Redirecting stdout to “nothing” in python, print will show nothing
Cross-platform:
import os
import sys
f = open(os.devnull, 'w')
sys.stdout = f
On Windows:
f = open('nul', 'w')
sys.stdout = f
On Linux:
f = open('/dev/null', 'w')
sys.stdout = f
examples : ping program
import subprocess as sub
p1 = sub.call('ping -c %s) %ip , shell =True,stderr = sub.STDOUT)
if p1 == 0 :
print "the server %s is alive'%ip
return ret
import subprocess as sub
ret = sub.Popen('uname -sv', shell =True, stdout = sub.PIPE)
uname = ret.stdout.read().strip()
print (unmae)
'Linux #1 SMP Tue Feb 12 02:46:46 UTC 2008'