问题
We have:
- A Python based server (A)
- A running command-line application (on the same Linux machine) which is able to read
stdin
, computes something and provides the output intostdout
(B)
What is the best (most elegant) way how to send an input from (A) to stdin
of (B), and wait for an answer from (B), i.e read its stdout
?
回答1:
As @Deestan pointed subprocess,module, is an elegant and proven one. We use subprocess a lot when we have to run commands from python.
Ours mostly involves running a command, mostly in-house built, and capturing its output. Our wrapper to run such commands looks thus.
import subprocess
def _run_command( _args, input=[],withShell=False):
"""
Pass args as array, like ['echo', 'hello']
Waits for completion and returns
tuple (returncode, stdout, stderr)
"""
p = subprocess.Popen(_args, shell = withShell,
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
[p.stdin.write(v) for v in input]
stdout, stderr = p.communicate()
return p.returncode, stdout, stderr
_,op,er = _run_command(['cat'],["this","is","for","testing"])
value="".join(op)
print value
_,op,er = _run_command(['ls',"/tmp"])
value="".join(op)
print value
If your input to B is minimal then subprocess is a yes.
回答2:
If you spawn (B) using Python's subprocess
module from the standard library, you can set up (B)'s stdin
and stdout
as byte buffers readable and writable by (A).
b = Popen(["b.exe"], stdin=PIPE, stdout=PIPE)
b.stdin.write("OHAI\n")
print(b.stdout.readline())
For your given example, it's easiest to use communicate
, as that takes care to avoid deadlocks for you:
b = Popen(["b.exe"], stdin=PIPE, stdout=PIPE)
b_out = b.communicate("OHAI\n")[0]
print(b_out)
http://docs.python.org/release/3.1.3/library/subprocess.html
http://docs.python.org/release/3.1.3/library/subprocess.html#subprocess.Popen.communicate
If there's a lot of 2-way communication, you should take care to avoid deadlocks because of full buffers. If your communication pattern gives this type of problem, you should consider using socket
communication instead.
来源:https://stackoverflow.com/questions/10188389/communicating-with-a-running-process