简体   繁体   中英

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?

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.)

Try this way

from subprocess import Popen, PIPE
import shlex
with open (filename, 'w') as fileHandle
proc = Popen(shlex.split(command), stdin = PIPE, stdout = PIPE, stderr  = PIPE)
out, err = proc.communicate(input = '\n')
print out, err

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM