11

How to achieve the following functionality:

  1. Python executes a shell command, which waits for the user to input something
  2. after the user typed the input, the program responses with some output
  3. Python captures the output
xiaohan2012
  • 9,870
  • 23
  • 67
  • 101
  • 3
    Take a look at [subprocess module](http://docs.python.org/library/subprocess.html). – RanRag May 20 '12 at 12:02
  • In a more general case [pexpect](http://www.noah.org/python/pexpect/) might be useful. – jfs May 20 '12 at 12:23

2 Answers2

12

You probably want subprocess.Popen. To communicate with the process, you'd use the communicate method.

e.g.

process=subprocess.Popen(['command','--option','foo'],
                         stdin=subprocess.PIPE,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE)
inputdata="This is the string I will send to the process"
stdoutdata,stderrdata=process.communicate(input=inputdata)
mgilson
  • 300,191
  • 65
  • 633
  • 696
1

For sync behaviors, you can use subprocess.run() function starting from Python v3.5.

As mentioned in What is the difference between subprocess.popen and subprocess.run 's accepted answer:

The main difference is that subprocess.run executes a command and waits for it to finish, while with subprocess.Popen you can continue doing your stuff while the process finishes and then just repeatedly call subprocess.communicate yourself to pass and receive data to your process.

SeleM
  • 9,310
  • 5
  • 32
  • 51