How to achieve the following functionality:
input
somethinginput
, the program responses with some output
output
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!
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.
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)
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 withsubprocess.Popen
you can continue doing your stuff while the process finishes and then just repeatedly callsubprocess.communicate
yourself to pass and receive data to your process.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With