2010-02-09 82 views
1

可能重複:
How to get output from subprocess.Popen()
Retrieving the output of subprocess.call()Python的子進程得到孩子的輸出

這裏是我的問題。我有一個名爲device_console的可執行文件。 device_console爲設備提供命令行界面。在device_console中,可以運行四個命令:狀態,列表,清除和退出。每個命令產生一個輸出。舉個例子:

[[email protected] ~]$ device_console 

device_console> list 

File A 

File B 

device_console> status 
Status: OK 

device_console> clear 
All files cleared 

device_console> list 
device_console> exit 

[[email protected] ~]$ 

作爲測試的一部分,我想要得到每個命令的輸出。我想爲它使用Python。我正在看Python的子進程,但不知何故,我無法將它們放在一起。你能幫忙嗎?

+0

所有這些的副本:http://stackoverflow.com/search?q=%5Bpython%5D+subprocess+output。特別是,http://stackoverflow.com/questions/1388753/how-to-get-output-from-subprocess-popen只是許多重複之一。 – 2010-02-09 11:19:25

回答

2

這聽起來像你想要更像'期待'的東西。

退房Pexpect

「Pexpect的是一個純粹的Python模塊 使的Python 控制和自動化等 程序的更好的工具。Pexpect的類似於 多恩·利伯斯Expect系統,但Pexpect的 作爲不同的界面, 更容易理解,Pexpect基本上是 模式匹配系統 它運行程序和手錶輸出 當輸出匹配給定模式 Pexpect可以響應,就好像人類對 鍵入響應一樣。「

+0

謝謝。我也會考慮Pexpect。 – innvtt 2010-02-09 14:23:49

2

使用subprocess module。示例:

import subprocess 

# Open the subprocess 
proc = subprocess.open('device_console', stdin=subprocess.PIPE, stdout.subprocess.PIPE) 

# Write a command 
proc.stdin.write('list\n') 

# Read the results back -- this will block until a line of input is received 
listing = proc.stdout.readline() 

# When you're done, close the input stream so the subprocess knows to exit 
proc.stdin.close() 

# Wait for subprocess to exit (optional) and get its exit status 
exit_status = proc.wait()