2013-07-09 13 views
9

Aşağıdaki kodu çalıştırırken bir hata alıyorum.check_output hatası

#!/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']) 

Hata

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

Ben Python 2.6.4 üzerinde çalışıyorum.

+0

Tanımlayan 'check_output 'yöntemini kullanmak mı istiyorsunuz? –

+0

Bunu yapmanın çok güzel bir yolu var, gerekli olup olmadığını tespit etmek de dahil olmak üzere, [bu yanıt] 'da (http://stackoverflow.com/a/13160748/1194883). – Mike

cevap

5

Hemen kullanın: Kendi fonksiyonunu tanımladığınız

check_output(['./MyFile']) 

, bu subprocess modülün bir nitelik değil (Python 2.6 için ve öncesi).

Ayrıca ithal modül nesnesine fonksiyon atayabilirsiniz (ancak bu gerekli değil):

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

'Dosya check_output olarak "DailyCheck.py", satır 19, ([ './ myFile']) Dosya "DailyCheck.py", check_output işlemde hat 5, = subprocess.Popen (stdout'u = subprocess.PIPE , * popenargs, ** kwargs) Dosya "/usr/lib/python2.6/subprocess.py", satır 621, in __init__ errread, errwrite) Dosya "/usr/lib/python2.6/subprocess.py ", satır 1126, _execute_child içinde yükseltmek child_exception OSError: [Errno 2] Böyle bir dosya veya dizin yok. Eminim bu hatayı alıyorum. Dosya belirtilen klasörde kesinlikle var. – misguided

+1

'os.getcwd() 'nin değerini kontrol etmeyi deneyin, doğru (MyFile'ın bulunduğu dizin olmalı). –

+0

@TravisGD Haklısınız. Yanlışlıkla os.chdir (konum) 'u sildim, dolayısıyla hatayı alıyordum. – misguided

7

Sen muhtemelen sadece şunu bil ki, check_output kullanmak istiyorum, ama bir yöntem yoktur subprocess.check_output, ancak Python 2.7 (http://docs.python.org/3/library/subprocess.html#subprocess.check_output)

Modüldeki işlevi tanımlayana kadar tanımlanamaz (v2.7'den önce çalışıyor).

try: subprocess.check_output 
except: subprocess.check_output = check_output 
subprocess.check_output() 
+0

Bunu yapmanın daha iyi bir yolu [bu yanıt] 'da verilmiştir (http://stackoverflow.com/a/13160748/1194883). – Mike