Python Execute Command Line,sending Input And Reading Output
How to achieve the following functionality: Python executes a shell command, which waits for the user to input something after the user typed the input, the program responses with
Solution 1:
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)
Solution 2:
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.
Post a Comment for "Python Execute Command Line,sending Input And Reading Output"