A communicate() method, which makes it easy to send stdin data and read stdout and stderr data, without risking deadlocks. Most people are aware of the flow control issues involved with child process communication, but not all have the patience or skills to write a fully correct and deadlock-free select loop. This means that many Python applications contain race conditions. A communicate() method in the standard library solves this problem.
Is there a way to have a bash process running in the background continuously and then the python calls could just go directly to that process?
subprocess.Popen
更复杂一些。它实际上创建了一个I/O线程来避免死锁。见https://www.python.org/dev/peps/pep-0324/:当然,您仍然可以使用
subprocess.Popen
,向子进程发送消息,并在不终止子进程的情况下接收消息。在最简单的情况下,您的消息可以是行。当子流程在发生感兴趣的事件时可以继续向您发送消息时,这允许使用请求-响应样式协议以及发布-订阅。
subprocess
除非明确要求,否则不要运行shell,例如此调用运行
ls
程序,而不调用/bin/sh
。如果您的子进程调用实际使用shell,例如specify a pipeline consicely或使用bash process substitution,这可能是冗长且容易出错的,从而直接使用
subprocess
模块定义,则调用bash
不太可能是性能瓶颈--请首先度量它。有些Python包也允许一致地指定这样的命令,例如^{} could be used to emulate a shell pipeline 。
如果您想使用} 对于与外部进程的基于对话框的交互很有用——尽管它不太可能影响时间性能。^{} 允许运行本地和远程命令(
bash
作为服务器进程,那么^{ssh
)。还有其他子流程包装器,如^{} ,它们可以解析字符串中指定的管道,而不调用shell,例如,它在Unix上启用cross-platform support for bash-like syntax (^{}, ^{}, ^{} in command lines) 或^{} ——一个在默认情况下提供TTY的完整} shell的命令。
同样,在大多数情况下,它不太可能以有意义的方式影响性能。
subprocess
替换(它看起来功能齐全,但the shell-like piping is less straightforward)。您甚至可以使用Python-ish-BASHwards-looking语法来运行带有^{以可移植的方式启动和与外部进程通信的问题很复杂——进程、管道、tty、信号、线程、异步之间的交互。IO,不同地方的缓冲有粗糙的边缘。如果您不知道一个特定的包如何解决与运行shell命令相关的许多问题,那么引入一个新包可能会使事情复杂化。
相关问题 更多 >
编程相关推荐