我正在尝试编写一个脚本,它必须对一些bash命令进行大量调用,解析并处理输出,最后给出一些输出.
我正在使用subprocess.Popen和subprocess.call
如果我理解正确这些方法产生一个bah进程,运行命令,获取输出然后终止进程.
有没有办法让bash进程在后台持续运行,然后python调用可以直接进入该进程?这就像bash作为服务器运行和python调用一样.
我觉得这会优化调用,因为没有bash进程设置和拆卸.或者它不会带来性能优势?
解决方法:
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 sendstdin
data and readstdout
andstderr
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. Acommunicate()
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并向您发送消息子进程并接收消息而不终止子进程.在最简单的情况下,您的消息可以是行.
当子进程可以在感兴趣的事件发生时继续向您发送消息时,这允许请求 – 响应样式协议以及发布 – 订阅.