2012-03-16 195 views
7

我需要從python運行這個linux命令並將輸出分配給一個變量。從python運行linux命令

ps -ef | grep rtptransmit | grep -v grep 

我試過使用pythons命令庫來做到這一點。

import commands 
a = commands.getoutput('ps -ef | grep rtptransmit | grep -v grep') 

但一個得到切斷的結束。我得到的輸出是:

'nvr  20714 20711 0 10:39 ?  00:00:00 /opt/americandynamics/venvr/bin/rtptransmit setup_req db=media camera=6 stream=video substream=1 client_a' 

但預期輸出是:

nvr  20714 20711 0 10:39 ?  00:00:00 /opt/americandynamics/venvr/bin/rtptransmit setup_req db=media camera=6 stream=video substream=1 client_address=192.168.200.179 client_rtp_port=6970 override_lockout=1 clienttype=1 

有誰知道如何從被截斷停止輸出或任何人可以提出另一種方法?

回答

8

ps顯然限制了它的輸出以裝配到終端的假定寬度。您可以使用$COLUMNS環境變量或使用--columns選項覆蓋此寬度至ps

commands模塊已棄用。使用subprocess獲取ps -ef的輸出並在Python中過濾輸出。不要使用shell=True其他答案的建議,正是在這種情況下,根本是多餘的:

ps = subprocess.Popen(['ps', '-ef', '--columns', '1000'], stdout=subprocess.PIPE) 
output = ps.communicate()[0] 
for line in output.splitlines(): 
    if 'rtptransmit' in line: 
     print(line) 

你也可以給你看的pgrep命令,通過它可以直接搜索特定的進程。

3

我通常使用subprocess來運行外部命令。對於你的情況,你可以這樣做以下

from subprocess import Popen, PIPE 

p = Popen('ps -ef | grep rtptransmit | grep -v grep', shell=True, 
      stdout=PIPE, stderr=PIPE) 
out, err = p.communicate() 

輸出將在out變量。

+1

-1無用的'grep'和'shell = True'。 – lunaryorn 2012-03-16 10:58:56

+0

如果您想在命令中使用管道,則需要'shell'。關於'grep',我實際上只是複製並粘貼了問題中的命令。我懷疑那是第二個'grep',因爲有時我們執行的'grep'命令也顯示爲grep-ed,因此需要刪除。這實際上可以避免使用'grep [r] tptransmit' – fajran 2012-03-16 11:02:46

+0

我知道'shell = True'需要在命令中使用管道,並且第二個'grep'將從第一個'grep'命令中刪除過濾的過程列表。但是在這種情況下,管道和'grep'都是多餘的。 – lunaryorn 2012-03-16 11:07:13

4

commands已棄用,不應使用它。使用subprocess代替

import subprocess 
a = subprocess.check_output('ps -ef | grep rtptransmit | grep -v grep', shell=True) 
+2

-1代表無用的'grep'和'shell = True'。 – lunaryorn 2012-03-16 10:58:48

+0

@lunaryorn:問題是如何在Python中運行該命令,而不是如何在Python中運行該命令。 – vartec 2012-03-16 11:09:46

+0

其實問題是如何避免截斷'ps'輸出。但是這並不矛盾我的觀點... – lunaryorn 2012-03-16 11:12:18