Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python subprocess write new line to stdin until process ends

I've created a subprocess using

subprocess.Popen(shlex.split(command), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

The command it calls will print various information, and then wait for a \n before printing more information. Eventually, the process will end when \n has been pressed enough times. I need to be able to programatically simulate the pressing of \n until the process ends, as well as capturing all output. I do not want the output to be printed to the Terminal. I would like it to be returned and set to a variable.

How would I do this?

like image 375
Nate Higgins Avatar asked Oct 26 '25 11:10

Nate Higgins


1 Answers

If you just have to write to stdin once, you could use

proc = subprocess.Popen(..., stdin = subprocess.PIPE)
proc.stdin.write('\n')

However, if you need to wait for a prompt or interact with the subprocess in a more complicated way, then use pexpect. (pexpect works with any POSIX system, or Windows with Cygwin.)

like image 143
unutbu Avatar answered Oct 29 '25 09:10

unutbu