您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

python – 是subprocess.Popen不线程安全吗?

5b51 2022/1/14 8:22:28 python 字数 3493 阅读 585 来源 www.jb51.cc/python

以下简单的脚本暂停在子进程上.Popen调用间歇性(大约30%的时间). 除非use_lock = True,否则它永远不会挂起,导致我相信子进程不是线程安全的! 预期的行为是脚本在5-6秒内完成. 为了演示错误,只需运行“ python bugProof.py”,直到挂起. Ctrl-C退出.你会看到’post-popen’只出现一次或两次,但不是第三次. import subprocess,

概述

import subprocess,threading,fcntl,os,time
end_time = time.time()+5
lock = threading.Lock()
use_lock = False
path_to_factorial = os.path.join(os.path.dirname(os.path.realpath(__file__)),'factorial.sh')

def testFunction():
    print threading.current_thread().name,'| pre-Popen'
    if use_lock: lock.acquire()
    p = subprocess.Popen([path_to_factorial],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    if use_lock: lock.release()
    print threading.current_thread().name,'| post-Popen'
    fcntl.fcntl(p.stdout,fcntl.F_SETFL,os.O_NONBLOCK)
    fcntl.fcntl(p.stderr,os.O_NONBLOCK)
    while time.time()<end_time:
        try: p.stdout.read()
        except: pass
        try: p.stderr.read()
        except: pass
    print threading.current_thread().name,'| DONE'

for i in range(3):
    threading.Thread(target=testFunction).start()

上面引用的shell脚本(factorial.sh):

#!/bin/sh
echo "Calculating factorial (anything that's somewhat compute intensive,this script takes 3 sec on my machine"
ans=1
counter=0
fact=999
while [ $fact -ne $counter ]
do
    counter=`expr $counter + 1`
    ans=`expr $ans \* $counter`
done
echo "Factorial calculation done"
read -p "Test input (this part is critical for bug to occur): " buf
echo "$buf"

系统信息:
Linux 2.6.32-358.123.2.openstack.el6.x86_64#1 SMP Thu Sep 26 17:14:58 EDT 2013 x86_64 x86_64 x86_64 GNU / Linux
Python 2.7.3(认,2013年1月22日,11:34:30)
[GCC 4.4.6 20120305(Red Hat 4.4.6-4)]在linux2上

在Python 3.2中对Python进行了大量的修改,它解决了这些问题(除了别的以外,fork和exec代码在C模块中,而不是在fork和exec之间的关键部分中进行了一些合理的Python代码),而且可用于subprocess32模块中最近的Python 2.x版本.请注意PyPI页面中的以下内容:“在POSIX系统上,在线程应用程序中使用时可保证其可靠”.

我可以重现偶然的(约25%的我)崩溃的上面的代码,但使用import subprocess32作为子进程,我没有看到任何失败在100运行.

请注意,subprocess32(和Python 3.2)认为close_fds = True,但是使用subprocess32,即使close_fds = False也不会发生任何故障(而不是您一般需要的).

总结

以上是编程之家为你收集整理的python – 是subprocess.Popen不线程安全吗?全部内容,希望文章能够帮你解决python – 是subprocess.Popen不线程安全吗?所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶