Reputation: 4081
Why if I run subprocess.check_output('ls')
everything is working but when I add argument to command like: subprocess.check_output('ls -la')
I get error:
Traceback (most recent call last):
File "", line 1, in
File "/usr/lib/python2.7/subprocess.py", line 537, in check_output
process = Popen(stdout=PIPE, *popenargs, **kwargs)
File "/usr/lib/python2.7/subprocess.py", line 679, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1259, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
How can I pass command arguments into subprocess.check_output()
?
Upvotes: 2
Views: 3639
Reputation: 1121406
You need to split the arguments into a list:
subprocess.check_output(['ls', '-la'])
The subprocess
callables do not parse the command out to individual arguments like the shell does. You either need to do this yourself or you need to tell subprocess
to use the shell explicitly:
subprocess.check_output('ls -la', shell=True)
The latter is not recommended as it can expose your application to security vulnerabilities. You can use shlex.split()
to parse a shell-like command line if needed:
>>> import shlex
>>> shlex.split('ls -la')
['ls', '-la']
Upvotes: 6