2016-11-14 86 views
1

我在AIX 6.1上運行並使用Python 2.7。想要執行以下行,但出現錯誤。獲取錯誤 - AttributeError:'module'對象在運行subprocess.run([「ls」,「-l」])時沒有屬性'run'

subprocess.run(["ls", "-l"]) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
AttributeError: 'module' object has no attribute 'run' 
+0

'subprocess'不應該(並且不......)有一個叫做'run'的方法。 – DeepSpace

+0

@DeepSpace它在Python 3中執行https://docs.python.org/3/library/subprocess.html#subprocess.run,但不幸的是,他們正在使用Python 2 –

+1

@MosesKoledoye嗯,這個問題是用'python 2.7 ';) – DeepSpace

回答

6

subprocess.run() function只存在於Python 3.5及更新版本中。

,這很容易然而,反向移植:

def run(*popenargs, input=None, check=False, **kwargs): 
    if input is not None: 
     if 'stdin' in kwargs: 
      raise ValueError('stdin and input arguments may not both be used.') 
     kwargs['stdin'] = subprocess.PIPE 

    process = subprocess.Popen(*popenargs, **kwargs): 
    try: 
     stdout, stderr = process.communicate(input) 
    except: 
     process.kill() 
     process.wait() 
     raise 
    retcode = process.poll() 
    if check and retcode: 
     raise subprocess.CalledProcessError(
      retcode, process.args, output=stdout, stderr=stderr) 
    return retcode, stdout, stderr 

沒有爲超時的支持,併爲完成過程信息沒有自定義類,所以我只能返回retcodestdoutstderr信息。否則它會和原來的一樣。

相關問題