簡體   English   中英

我如何從已執行的Shell命令讀取輸出?

[英]How can i read the output from an executed shell command?

我已經閱讀了許多有關此主題的問題,甚至有2個已經接受了答案,然后在評論中出現了與我所遇到的問題相同的問題。

所以我想做的就是捕獲此命令的輸出(在命令行中有效)

 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安裝上),為什么呢?

我相信您要做的就是改變,

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

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

當我在args列表中將多個參數作為單個字符串包含在內時,會出現相同的錯誤。

到的參數Popen需要一個列表,你可以使用shlex自動為您處理這個

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

產生

['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句柄,您需要與該subprocess句柄進行communicate以獲得輸出。 注意-添加stderr=PIPE將使您可以訪問STDERRSTDOUT

您可以使用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

help()

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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM