Python调用subprocess.Popen卡死

本文共有1197个字,关键词:

问题:subprocess.popen进程卡死如何解决?

解决:原因是subprocess的PIPE是有大小的。在python2.6.11之前,PIPE的大小为文件页的大小(i386上是4096),2.6.11之后变为65536.因此当输出内容超过65536,会引起阻塞。因为PIPE已经被塞满了,无法再塞进更多的数据。
解决方法是不用subprocess提供的PIPE,或者不要实时输出执行命令后的输出内容。

方法:

obj = subprocess.Popen(cmd,stdout=fileno,stderr=fileno,shell=True)
obj.communicate()

关闭输出内容

from subprocess import DEVNULL, STDOUT, check_call
check_call([cmd, arg1, arg2], stdout=DEVNULL, stderr=STDOUT)

with open(os.devnull, 'w') as fp:
    cmd = subprocess.Popen(("[command]",), stdout=fp)

拓展:
将日志文件别存到别处,只有当错误时输出

# 运行脚本
cmd_str = 'bash /bin/hellog.sh 2024'
logout = os.path.realpath(os.path.join(os.path.dirname(__file__), "logs/stdout.log"))
with open(logout, 'w') as fp:
    p = subprocess.Popen(cmd_str, shell=True, executable='bash', stdout=fp, stderr=subprocess.PIPE)
    stdout, stderr = p.communicate()
    if stderr:
        return {'code': 1, 'msg': stderr, 'pid': p.pid}

return {'code': 0, 'pid': p.pid

参考:

https://blog.csdn.net/losemyheaven/article/details/48159855 评论中的内容
https://www.cnpython.com/qa/59709
版权声明:本文为作者原创,如需转载须联系作者本人同意,未经作者本人同意不得擅自转载。
添加新评论
暂无评论