前段时间在用Python做一个项目时,遇到了这样一个问题:用python自带的多线程库threading 实现并发管道操作时,使用os.popen根本无法做到真正的并发执行。琢磨了半天,才找到解决办法,具体示例见下:
import threading, os, subprocess
def Execute_popen(cmd):
""""""
print "popen"
os.popen(cmd)
def Execute_subproc(cmd):
""""""
print "subproc"
pipe = subprocess.Popen("cmd.exe", stdin = subprocess.PIPE, stdout = subprocess.PIPE,
stderr = subprocess.PIPE, shell = True)
pipe.communicate('%s\n' % cmd)
def test():
""""""
cmd = "ping 127.0.0.1"
for i in xrange(5):
_thread_popen = threading.Thread(target = Execute_popen, args = (cmd,))
_thread_popen.start()