我们有:
stdin、计算某些内容并将输出提供给stdout(B)如何将输入从(A)发送到stdin(B)并等待(B)的答案(即读取其)的最佳(最优雅)方法是什么stdout?
正如@Deestan 指出的,子流程、模块是一个优雅且经过验证的流程。当我们必须从 python 运行命令时,我们经常使用子进程。
我们的主要涉及运行命令(主要是内部构建的)并捕获其输出。我们运行此类命令的包装器看起来如下。
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
Run Code Online (Sandbox Code Playgroud)
如果您对B 的输入很少,则 subprocess 为yes。
| 归档时间: |
|
| 查看次数: |
9307 次 |
| 最近记录: |