Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python execute command line,sending input and reading output

Tags:

python

io

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
like image 469
xiaohan2012 Avatar asked May 20 '12 11:05

xiaohan2012


People also ask

How do you execute a command line in Python?

To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World! If everything works okay, after you press Enter , you'll see the phrase Hello World!

How do you give a Python script a command line input?

If so, you'll need to use the input() command. The input() command allows you to require a user to enter a string or number while a program is running. The input() method replaced the old raw_input() method that existed in Python v2. Open a terminal and run the python command to access Python.


2 Answers

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)
like image 119
mgilson Avatar answered Sep 28 '22 18:09

mgilson


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.

like image 30
SeleM Avatar answered Sep 28 '22 17:09

SeleM