1

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?

Community
  • 1
  • 1
innvtt
  • 11
  • 2
  • Duplicate of all of these: http://stackoverflow.com/search?q=%5Bpython%5D+subprocess+output. Specifically, http://stackoverflow.com/questions/1388753/how-to-get-output-from-subprocess-popen as just one of many exact duplicates. – S.Lott Feb 09 '10 at 11:19

2 Answers2

2

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."

Corey Goldberg
  • 59,062
  • 28
  • 129
  • 143
2

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()
Adam Rosenfield
  • 390,455
  • 97
  • 512
  • 589