Python subprocess get child's output [duplicate]
Possible Duplicates:
How to get output from subprocess.Popen() Retrieving the output of subprocess.call()
Here is my question. I have an executable called device_console. The device_console provides a command line interface to a device. In device_console, four commands can be run: status, list, clear and exit. Each command produces an output. As an example:
[asdfgf@localhost ~]$ 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
[asdfgf@localhost ~]$
As part of testing, I want to get the output of each command. I want to use Python for it. I am looking at Python's subprocess, but somehow I am unable to put them together. Can you please help开发者_StackOverflow中文版?
Use the subprocess
module. Example:
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()
it sounds like you want something more like 'Expect'.
check out Pexpect
"Pexpect is a pure Python module that makes Python a better tool for controlling and automating other programs. Pexpect is similar to the Don Libes
Expect
system, but Pexpect as a different interface that is easier to understand. Pexpect is basically a pattern matching system. It runs programs and watches output. When output matches a given pattern Pexpect can respond as if a human were typing responses."
精彩评论