关于Python中并发调用管道执行外部程序的问题解决

本文介绍了在Python中遇到的并发管道执行外部程序问题,通过对比os.popen和subprocess.popen,揭示了os.popen在多线程环境下无法实现并发的实际情况,并建议使用subprocess代替os.popen来实现并行操作,通过示例代码展示了subprocess.popen在并发执行中的正确效果。
摘要由CSDN通过智能技术生成

前段时间在用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()
        
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值