From the python document http://docs.python.org/2/library/subprocess.html
If I type the following in python
>>> subprocess.call(["ls", "-l"])
I will get a 0.
If I type the following in python,
>>> subprocess.call("exit 1", shell=True)
I will get a 1. However, if I type
>>> subprocess.call("exit 1")
It will show me an error
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/subprocess.py", line 493, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib/python2.7/subprocess.py", line 679, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1249, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
Why does this happen?
Second question, if ls
crashes, will I get a non-zero return value by using the following command?
>>> subprocess.call(["ls", "-l"])
exit
is a shell routine, not a real program. You get an error because the call can not find a program named exit
. If you don't set the shell
argument to True
this makes no sense to executing it.
To answer your second question, yes you will get an non-zero returning value. Try listing a directory in which you don't have read rights.
This is because if shell=True
the command will be executed through a shell. You can pass a command line like in a shell. If you omit that param, the first param is threatened as a file name, the file name of the command. and there is no command 'exit 1'
Here comes another example using the ls -al
command:
import subprocess
subprocess.call("ls -al", shell=True) # works
subprocess.call("ls -al") # fails
Also note the answer of @ibi0tux regarding exit
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.