preethy tulpi
preethy tulpi

Reputation: 415

subprocess checkouput OSError: [Errno 2] No such file or directory

Below is example code:

from subprocess import check_output
list1 = ['df', 'df -h']
for x in list1:
    output = check_output([x])

Getting below error for list1 of dh -h value.

File "/usr/lib64/python2.7/subprocess.py", line 568, in check_output
  process = Popen(stdout=PIPE, *popenargs, **kwargs)
File "/usr/lib64/python2.7/subprocess.py", line 711, in __init__
  errread, errwrite)
File "/usr/lib64/python2.7/subprocess.py", line 1327, in _execute_child
  raise child_exception
OSError: [Errno 2] No such file or directory

what is best method to read linux command output's in python2.7

Upvotes: 1

Views: 3816

Answers (3)

Guy
Guy

Reputation: 647

There are a few options with this situation, for ways of passing a cmd and args:

# a list broken into individual parts, can be passed with `shell=False
['cmd', 'arg1', 'arg2', ... ]
# a string with just a `cmd`, can be passed with `shell=False`
'cmd`
# a string with a `cmd` and `args` 
# can only be passed to subprocess functions with `shell=True`
'cmd arg1 arg2 ...'

Just to follow up on mariis answer. The subprocess docs on python.org have more info on why you may want to pick one of a couple of options.

args is required for all calls and should be a string, or a sequence of program arguments. Providing a sequence of arguments is generally preferred, as it allows the module to take care of any required escaping and quoting of arguments (e.g. to permit spaces in file names). If passing a single string, either shell must be True (see below) or else the string must simply name the program to be executed without specifying any arguments.

(emphesis added)

While adding shell=True would be OK for this, it's recommended to avoid, as changing 'df -h' to ['df', '-h'] isn't very difficult, and is a good habit to get into, only using the shell if you really need to. As the docs also add, against a red background no less:

Warning. Executing shell commands that incorporate unsanitized input from an untrusted source makes a program vulnerable to shell injection, a serious security flaw which can result in arbitrary command execution. For this reason, the use of shell=True is strongly discouraged in cases where the command string is constructed from external input

Upvotes: 0

ZhouQuan
ZhouQuan

Reputation: 1067

I recommend delegator written by kennethreitz, with his package https://github.com/kennethreitz/delegator.py, you can simply do, and both the API and output is cleaner:

import delegator

cmds = ['df', 'df -h']
for cmd in cmds:
    p = delegator.run(cmd)
    print(p.out)

Upvotes: 0

Mariy
Mariy

Reputation: 5924

You should provide check_output arguments as a list. This works:

from subprocess import check_output
list1 = ['df', 'df -h']
for x in list1:
    output = check_output(x.split())

Upvotes: 2

Related Questions