概述
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不线程安全吗?所遇到的程序开发问题。
如果您也喜欢它,动动您的小指点个赞吧