2011-07-18 123 views
2

可能重複:
Running shell command from python and capturing the outputPython的命令執行輸出

欲一個命令的輸出捕獲到一個變量,所以後來該變量可被再次使用。我需要改變這個腳本,它是:

#!/usr/bin/python 
import os 
command = raw_input("Enter command: ") 
os.system(command) 

如果我輸入「LS」當我運行該腳本,我得到這樣的輸出:

Documents Downloads Music Pictures Public Templates Videos 

我希望捕獲的字符串(輸出ls命令)到一個變量中,以便稍後再使用它。我該怎麼做呢?

回答

9
import subprocess 
command = raw_input("Enter command: ") 
p = subprocess.Popen(command, stdout=subprocess.PIPE) 
output, error = p.communicate() 
0

這是我過去的做法。

>>> import popen2 
__main__:1: DeprecationWarning: The popen2 module is deprecated. Use the subprocess module. 
>>> exec_cmd = popen2.popen4("echo shell test") 
>>> output = exec_cmd[0].read() 
>>> output 
'shell test\n' 
+0

所有舊的popen接口都被棄用,以支持子流程。 –

+0

@Chris我想知道什麼「DeprecationWarning:popen2模塊已棄用,請使用子流程模塊。」意思是... – ironchefpython

+0

諷刺。是的,我聽說過這樣的事情。 –