As previously described, you can (and should) use the subprocess module.
By default, shell
parameter is False
. This is good, and quite safe. Also, you don't need to pass the full path, just pass the executable name and the arguments as a sequence (tuple or list).
import subprocess
# This works fine
p = subprocess.Popen(["echo","2"])
# These will raise OSError exception:
p = subprocess.Popen("echo 2")
p = subprocess.Popen(["echo 2"])
p = subprocess.Popen(["echa", "2"])
You can also use these two convenience functions already defined in subprocess module:
# Their arguments are the same as the Popen constructor
retcode = subprocess.call(["echo", "2"])
subprocess.check_call(["echo", "2"])
Remember you can redirect stdout
and/or stderr
to PIPE
, and thus it won't be printed to the screen (but the output is still available for reading by your python program). By default, stdout
and stderr
are both None
, which means no redirection, which means they will use the same stdout/stderr as your python program.
Also, you can use shell=True
and redirect the stdout
.stderr
to a PIPE, and thus no message will be printed:
# This will work fine, but no output will be printed
p = subprocess.Popen("echo 2", shell=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# This will NOT raise an exception, and the shell error message is redirected to PIPE
p = subprocess.Popen("echa 2", shell=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)