2012-08-22 112 views
2

可能重複:
Running shell command from python and capturing the output簡單的python命令來捕獲shell執行輸出?

當我想捕捉shell執行輸出,我這樣做。

declare TAGNAME=`git describe --tags` 

簡單。我在Python中尋找這個,但其中大多數看起來非常複雜。什麼是最簡單的方法來做到這一點?是的,我知道我可以創建一個函數,但是我想知道預定義的函數是否存在。

tagname = theFunc('git describe --tags') 

回答

6

嘗試:

>>> import subprocess 
>>> tagname = subprocess.check_output('git describe --tags'.split()) 
+0

需要爲返回的字符串調用'.strip('\ n')'。 – Eonil

+0

@Eonil爲什麼要調用'.strip('\ n')'?擁有'\ n'真的很重要嗎? – quantum

+0

@xiaomao是的。因爲我會將字符串傳遞給另一個shell命令。如果你意想不到的結果會很好,那真是太好了。 – Eonil

1

你應該看看subprocess模塊。你也可以捕獲一個命令的輸出。手冊頁中有很多例子說明了如何使用模塊。

實施例:

output=subprocess.Popen(["ps", "aux"], stdout=subprocess.PIPE, 
    stderr=subprocess.PIPE).communicate() 

結果是具有輸出和錯誤一個元組是從命令捕獲。