10

I am gettin a error while running the below code.

#!/usr/bin/python
import subprocess
import os
def check_output(*popenargs, **kwargs):
    process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs)
    output, unused_err = process.communicate()
    retcode = process.poll()
    if retcode:
        cmd = kwargs.get("args")
        if cmd is None:
            cmd = popenargs[0]
        error = subprocess.CalledProcessError(retcode, cmd)
        error.output = output
        raise error
    return output

location = "%s/folder"%(os.environ["Home"])
subprocess.check_output(['./MyFile'])

Error

subprocess.check_output(['./MyFile'])
AttributeError: 'module' object has no attribute 'check_output'

I am working on Python 2.6.4 .

misguided
  • 3,699
  • 21
  • 54
  • 96

3 Answers3

7

You probably just want to use check_output, but, just so you know, there is a method subprocess.check_output, but it's not defined until Python 2.7 (http://docs.python.org/3/library/subprocess.html#subprocess.check_output)

You might even want this, which defines the function in the module if it's not there (i.e. running before v2.7).

try: subprocess.check_output
except: subprocess.check_output = check_output
subprocess.check_output()
Matt
  • 27,170
  • 6
  • 80
  • 74
Travis DePrato
  • 392
  • 3
  • 9
  • A nicer way to do that is given in [this answer](http://stackoverflow.com/a/13160748/1194883). – Mike Feb 17 '15 at 22:51
6

Just use :

check_output(['./MyFile'])

You've defined your own function, it's not an attribute of subprocess module(for Python 2.6 and earlier).

You can also assign the function to the imported module object(but that's not necessary):

subprocess.check_output = check_output
location = "%s/folder" % (os.environ["Home"])
subprocess.check_output(['./MyFile'])
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • `File "DailyCheck.py", line 19, in check_output(['./MyFile']) File "DailyCheck.py", line 5, in check_output process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs) File "/usr/lib/python2.6/subprocess.py", line 621, in __init__ errread, errwrite) File "/usr/lib/python2.6/subprocess.py", line 1126, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory` NOt sure why I am getting this error. The file is definitelythere in the folder specified. – misguided Jul 09 '13 at 04:43
  • 1
    Try checking the value of `os.getcwd()` is correct (should be the directory that MyFile is in). – Travis DePrato Jul 09 '13 at 04:44
  • @TravisGD you are correct. I had deleted `os.chdir(location)` by mistake , hence was getting the error. – misguided Jul 09 '13 at 04:51
0

try the following:

from subprocess import check_output 
print(check_output(["dir", "C:\\Downloads\\file.csv"],shell=True).decode("utf8"))

ensure that you have \ in your path rather than '/' and "dir" rather "ls"

E.Zolduoarrati
  • 1,539
  • 2
  • 9
  • 9