2015年8月18日 星期二

在 Python 2.6 執行指令並擷取回應

想要用 Python 執行某個指令,並且把指令回覆的資料拿來做後續的程式處理
在 Python 2.7 以上版本可以用 subprocess.check_output() 這個方法
不過看了一下文件,Python 2.6 似乎沒有 check_output 的方法,有的只有 Popen 而已。

底下的程式中,因為輸出的資料希望能夠以行為單位,因此使用了 StringIO 做行輸出:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import subprocess
import StringIO
 
def execute (program):
    '''
        Args:
            program - A list that contains the command for executing.
        Returns:
            A StringIO instance that contains the result of execution.
             
        Raises:
            IOError - Cannot send the command.
    '''
    try:
        proc = subprocess.Popen(program, stdout=subprocess.PIPE)
        process_res = proc.communicate()
        # Use StringIO to format the response into lines.
        return StringIO.StringIO(process_res[0])
    except OSError, e:
        print e.output
        raise IOError()
    except ValueError, e:
        print e.output
        raise IOError()
    except subprocess.CalledProcessError,e:
        print e.output
        raise IOError()

要執行指令時,以 List 的形式輸入指令給上述的 execute() 方法
execute() 回傳的 StringIO 就可以透過 readline() 的方式取得指令的回應。
1
2
3
4
5
6
7
8
9
10
11
12
program = ["/usr/sbin/gluster",
           "volume",
           "info",
           "vol"]
 
# Execute the command.
buf = runtime.execute(self.program)
 
# Parse the response.
while True:
    line = buf.readline()
    # Do whatever you want to parse the response.

參考資料:
  1. Setting output of a program to pipe in Python 2.6.6
  2. subprocess — Subprocess management

1 則留言:

Unknown 提到...

哈囉 請問我最近也想寫類似的工具,執行指令(例如ipconfig之類的)後,將指令的回應存成指定的檔案,可以請問大概要如何寫麻? 第一次寫 python。