2

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()?

0

2 Answers 2

6

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']
Sign up to request clarification or add additional context in comments.

Comments

0

You might find sh.py more friendly:

import sh

print sh.ls("-la")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.