2013-03-30 104 views
1

我已經閱讀了許多關於這個主題的問題,甚至2個已經接受了答案,然後在評論中有同樣的問題,我正在經歷。如何讀取執行的shell命令的輸出?

所以我想要做的就是抓住這個命令的輸出(在命令行工作)

sudo /usr/bin/atq 

在我的Python程序。

這是我的代碼(這是一個公認的答案在另一個問題)

from subprocess import Popen, PIPE 

output = Popen(['sudo /usr/bin/atq', ''], stdout=PIPE) 
print output.stdout.read() 

,這是結果:

File "try2.py", line 3, in <module> 
    output = Popen(['sudo /usr/bin/atq', ''], stdout=PIPE) 
    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 

爲什麼啊,爲什麼是這樣的結果(在Python 2.7,在Debian Raspbarry Wheezy上安裝)?

+0

嘗試'subprocess.check_output()'。 –

+0

什麼是快速回答....它的工作原理!你可以發佈它作爲答案... – Michel

+0

已經發布。 –

回答

3

Popen的參數必須是一個列表,你可以爲你

import shlex 
args = shlex.split('sudo /usr/bin/atq') 
print args 

自動使用shlex來處理這個產生

['sudo', '/usr/bin/atq'] 

然後你就可以傳遞給Popen。然後,您需要使用您創建的流程communicate。 有.communicate()一去(注參數Popen這裏有一個清單!)即

prc = Popen(['sudo', '/usr/bin/atq'], stdout=PIPE, stderr=PIPE) 
output, stderr = prc.communicate() 
print output 

Popen返回subprocess手柄,您需要communicate與得到的輸出。注 - 加入stderr=PIPE將使您可以訪問STDERR以及STDOUT

1

您可以使用subprocess.check_output()

subprocess.check_output(['sudo', '/usr/bin/atq']) 

例如:

In [11]: print subprocess.check_output(["ps"]) 
    PID TTY   TIME CMD 
4547 pts/0 00:00:00 bash 
4599 pts/0 00:00:00 python 
4607 pts/0 00:00:00 python 
4697 pts/0 00:00:00 ps 

幫助()

In [12]: subprocess.check_output? 
Type:  function 
String Form:<function check_output at 0xa0e9a74> 
File:  /usr/lib/python2.7/subprocess.py 
Definition: subprocess.check_output(*popenargs, **kwargs) 
Docstring: 
Run command with arguments and return its output as a byte string. 

If the exit code was non-zero it raises a CalledProcessError. The 
CalledProcessError object will have the return code in the returncode 
attribute and output in the output attribute. 

The arguments are the same as for the Popen constructor. 
6

我相信所有你需要做的是改變,

output = Popen(['sudo /usr/bin/atq'], stdout=PIPE) 

output = Popen(['sudo', '/usr/bin/atq'], stdout=PIPE) 

我得到同樣的錯誤,當我有多個參數作爲args列表中的一個字符串。