2012-11-20 166 views
2

我正在嘗試編寫一個python腳本,它允許我從命令中獲取輸出並將其放入一個文件或變量(Preferability一個變量)中。將輸出命令重定向到變量或文件?

在我的代碼中,我已將輸出重定向到一個StringIO()對象。從那裏,我想要輸出一個命令,並把它放入那個對象StringIO()

這裏是我的代碼示例:

from StringIO import StringIO 
import sys 

old_stdout = sys.stdout 

result = StringIO() 
sys.stdout = result 

# This will output to the screen, and not to the variable 
# I want this to output to the 'result' variable 
os.system('ls -l') 

而且,我怎麼拿得到,並把它轉換成字符串?

在此先感謝!

+0

[運行從蟒外殼命令和捕獲輸出]的可能重複(http://stackoverflow.com/questions/4760215/running-shell-command-from-python-and-capturing-the-output ) – DocMax

回答

5
import subprocess 
sp = subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE) 
output, _ = sp.communicate() 
print "Status:", sp.wait() 
print "Output:" 
print output 
+0

在我的真實代碼中,我沒有使用'ls -l'。我正在使用命令'find *'。當我使用'find *'代替你在註釋中的代碼中的'ls -l'時,它不會給出任何東西,但是當我轉到正常命令行時,它會輸出一切正常。當我使用'ls -l'時,它工作正常。建議? –

+0

您可以使用'Popen()'參數'shell = True'並給它一個要執行的字符串。或者你可以使用'['find','。']',它應該基本上是相同的,或多或少。 – glglgl

+0

酷!謝謝!這工作! –

相關問題