在python中替代子流程

2024-05-18 09:09:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图编写一个脚本,它必须对一些bash命令进行大量调用,解析和处理输出,最后给出一些输出。

我用的是subprocess.Popen和subprocess.call

如果我理解正确的话,这些方法生成一个bah进程,运行命令,获取输出,然后终止进程。

有没有办法让bash进程在后台连续运行,然后python调用就可以直接转到该进程?这将类似于bash作为服务器运行,python调用将访问它。

我觉得这会优化一些调用,因为没有bash进程的设置和拆卸。或者它不会给性能带来优势?


Tags: 方法命令服务器脚本bash进程call性能
2条回答

If I understand correct these methods spawn a bah process, run the command, get the output and then kill the process.

subprocess.Popen更复杂一些。它实际上创建了一个I/O线程来避免死锁。见https://www.python.org/dev/peps/pep-0324/

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 feel this would optimize the calls a bit as there is no bash process setup and teardown.

subprocess除非明确要求,否则不要运行shell,例如

#!/usr/bin/env python
import subprocess

subprocess.check_call(['ls', '-l'])

此调用运行ls程序,而不调用/bin/sh

Or will it give no performance advantage?

如果您的子进程调用实际使用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的完整subprocess替换(它看起来功能齐全,但the shell-like piping is less straightforward)。您甚至可以使用Python-ish-BASHwards-looking语法来运行带有^{}shell的命令。 同样,在大多数情况下,它不太可能以有意义的方式影响性能。

以可移植的方式启动和与外部进程通信的问题很复杂——进程、管道、tty、信号、线程、异步之间的交互。IO,不同地方的缓冲有粗糙的边缘。如果您不知道一个特定的包如何解决与运行shell命令相关的许多问题,那么引入一个新包可能会使事情复杂化。

相关问题 更多 >