欢迎访问 生活随笔!

尊龙游戏旗舰厅官网

当前位置: 尊龙游戏旗舰厅官网 > 编程语言 > python >内容正文

python

python subprocess使用记录 -尊龙游戏旗舰厅官网

发布时间:2025/1/21 python 23 豆豆
尊龙游戏旗舰厅官网 收集整理的这篇文章主要介绍了 python subprocess使用记录 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

2019独角兽企业重金招聘python工程师标准>>>

前几天发现服务器上有几个zombie进程,搜索了一下(ps -ef | grep defunct),僵尸进程的父进程是以前写的python同步脚本。

仔细看了下代码,发现在这:

sub = subprocess.popen(cmd, shell=true, stdout=subprocess.pipe, stderr=subprocess.stdout) # other codes

对,父进程开启了子进程后,并无任何动作,子进程执行完成后成为一个僵尸进程。

解决方法很简单,父进程wait子进程即可,但因为标准输出和标准错误输出是管道方式(pipe),直接使用wait()有可能会导致管道堵塞,python官方文档亦有以下叙述:

warningthis will deadlock when using stdout=pipe and/or stderr=pipe and the child process generates enough output to a pipe such that it blocks waiting for the os pipe buffer to accept more data. use communicate() to avoid that.

官方建议适用communicate方法,于是修改代码如下:

sub = subprocess.popen(cmd, shell=true, stdout=subprocess.pipe, stderr=subprocess.stdout) out, err = sub.communicate()

另外一种修改方式,适用于不关心子进程返回结果的场景,可以将stdout和stderr输出结果定向到/dev/dull去,再调用wait()即可,如下:

sub = subprocess.popen(cmd, shell=true, stdout=open("/dev/null", "w"), stderr=subprocess.stdout) sub.wait()

因为需要子进程的处理信息,选用了第一种方法。重新启动python脚本,不再出现僵尸进程的问题了。


转载于:https://my.oschina.net/catandpaperball/blog/477184

总结

以上是尊龙游戏旗舰厅官网为你收集整理的python subprocess使用记录的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得尊龙游戏旗舰厅官网网站内容还不错,欢迎将尊龙游戏旗舰厅官网推荐给好友。

网站地图