替代在Python子过程 [英] Alternative in python to subprocess

查看:145
本文介绍了替代在Python子过程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图写有做了很多电话在一定的bash命令,解析和处理输出的最后给出一些输出的脚本。

我使用subprocess.Popen和subprocess.call

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

有没有办法让在后台不断地再蟒蛇通话可能只是直接进入该进程中运行的bash进程?这将是类似的bash作为服务器运行和Python会调用它。

我觉得这将优化调用了一下,因为没有bash进程安装和拆卸。还是会给出任何性能优势?


解决方案

  

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


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


  

A 通讯()方法,它可以很容易地发送标准输入数据和读取标准输出标准错误数据,而不用担心死锁。大多数人都知道的涉及子进程的通信流量控制问题,但不是所有的耐心和技巧写一个完全正确的,无死锁选择循环。这意味着许多Python应用程序包含竞争条件。在标准库中的通讯()方法解决了这个问题。




  

有没有办法让在后台不断地再蟒蛇通话可能只是直接进入该进程中运行的bash进程?


当然,你仍然可以使用 subprocess.Popen 和你子过程和接收消息回而不终止子进程发送消息。在最简单的情况下,你的消息可以是线。

这允许请求 - 响应式的协议以及发布 - 订阅时,子进程可以继续发送邮件,你回来时,感兴趣的事件发生。

I am trying to write a script which has to make a lot of calls to some bash commands, parse and process the outputs and finally give some output.

I was using subprocess.Popen and subprocess.call

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

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? This would be something like bash running as a server and python calls going to it.

I feel this would optimize the calls a bit as there is no bash process setup and teardown. Or will it give no performance advantage?

解决方案

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

subprocess.Popen is a bit more involved. It actually creates an I/O thread to avoid deadlocks. See 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?

Sure, you can still use subprocess.Popen and send messages to you subprocess and receive messages back without terminating the subprocess. In the simplest case your messages can be lines.

This allows for request-response style protocols as well as publish-subscribe when the subprocess can keep sending you messages back when an event of interest happens.

这篇关于替代在Python子过程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆