本文介绍了与正在运行的进程进行通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我们有:
- 基于Python的服务器(A)
- 正在运行的命令行应用程序(在同一台Linux机器上),它能够读取
stdin
,计算内容并将输出提供给stdout
(B)
- 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)
如何将(A)的输入发送到(B)的stdin
并等待(B)的答案,即读取其stdout
的最佳方式(最优雅)?
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
?
推荐答案
正如@Deestan指出的子流程,模块一样,它是一个优雅且久经考验的模块.当我们必须从python运行命令时,我们会大量使用子进程.
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
如果您对 B 的输入最少,则子流程为是.
If your input to B is minimal then subprocess is a yes.
这篇关于与正在运行的进程进行通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!