Keep the subprocess and keep giving it commands? python

If I create a new subprocess in python with the given command (say, I started the python interpreter using the python command), how can I send new data to the process (via STDIN)?

+8
python subprocess process popen
source share
3 answers

Use the standard subprocess module. You use subprocess.Popen () to start the process, and it will run in the background (i.e., at the same time as your Python program). When you call Popen (), you probably want to set the stdin, stdout and stderr parameters for subprocess.PIPE. Then you can use the stdin, stdout and stderr fields for the returned object to write and read data.

Unverified code example:

 from subprocess import Popen, PIPE # Run "cat", which is a simple Linux program that prints it input. process = Popen(['/bin/cat'], stdin=PIPE, stdout=PIPE) process.stdin.write(b'Hello\n') process.stdin.flush() print(repr(process.stdout.readline())) # Should print 'Hello\n' process.stdin.write(b'World\n') process.stdin.flush() print(repr(process.stdout.readline())) # Should print 'World\n' # "cat" will exit when you close stdin. (Not all programs do this!) process.stdin.close() print('Waiting for cat to exit') process.wait() print('cat finished with return code %d' % process.returncode) 
+8
source share

Not.

If you want to send commands to a subprocess, create a pty, and then remake the subprocess from one end of the pty attached to its STDIN.

Here is a snippet from my code:

 RNULL = open('/dev/null', 'r') WNULL = open('/dev/null', 'w') master, slave = pty.openpty() print parsedCmd self.subp = Popen(parsedCmd, shell=False, stdin=RNULL, stdout=WNULL, stderr=slave) 

In this code, pty is attached to stderr because it accepts error messages rather than sending commands, but the principle is the same.

+3
source share

The tunnel created by Subprocess to run multiple commands cannot be saved. to achieve this, you can study paramiko, for other things like subprocess stdin, stdout, stderr, you can go through this link a python subprocess , since this is your first python project it is better to read and test the material.

0
source share

All Articles