2013-01-21 29 views
0

我想獲得linux機器上的第一個接口。我使用subproces,我有下面這段代碼:將系統命令的結果保存到使用子進程的變量中

def get_eth_iface(): 
    awk_sort = subprocess.Popen(["-c", "ifconfig | cut -d ' ' -f 1 | grep eth | head -n 1" ], stdin= subprocess.PIPE, shell=True) 
    awk_sort.wait() 
    output = awk_sort.communicate()[0] 

但是,這個結果將被打印到控制檯,並不會被保存到變量。我如何重定向到變量?

回答

1

重定向stdoutsubprocess.PIPE。以下爲我工作。

import subprocess 
def get_eth_iface(): 
    awk_sort = subprocess.Popen(["dir" ], stdin= subprocess.PIPE, stdout= subprocess.PIPE) 
    awk_sort.wait() 
    output = awk_sort.communicate()[0] 
    print output.rstrip() 
get_eth_iface() 
+0

好,感謝的作品不錯,但我不得不這樣做'輸出= awk_sort.communicate()[0]'獲得實際的接口名+我與新行標誌接口名稱。我怎樣才能擺脫這一點? – Patryk

+1

只需使用字符串上的rstrip方法即可。 – Holger

1

http://docs.python.org/2/library/subprocess.html

同樣,要獲得比無結果中的元組其他任何東西,你 需要給stdout=PIPE和/或stderr=PIPE過。

聽起來像一個很好的建議。添加stdout=subprocess.PIPE,看看會發生什麼。

相關問題