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
2
  • 3
    Take a look at subprocess module. Commented May 20, 2012 at 12:02
  • In a more general case pexpect might be useful. Commented May 20, 2012 at 12:23

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

What if i have 2 or more inputs and i want to run it in background so that i should see no console.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.