python 并发执行


(1)需要执行python 程序如下:

#!/usr/bin/env python
import os,sys
import threading
from time import sleep,ctime

IpFileName='iplist.txt'
shellFileName='shell.sh'
iplist=[]
 
class ThreadFunc(object):
       def __init__(self,func,args,name=''):
              self.name=name
              self.func=func
              self.args=args
       def __call__(self):
              self.res=self.func(*self.args)

def loop(i,ip):
    cmd='sh ' + shellFileName + ' ' + ip
    os.system(cmd)


def getIpList():
    path=os.getcwd()
    if os.path.isfile(path+'/'+IpFileName)==False:
        print 'file ' + path+'/'+IpFileName + ' does not exist.'
    fd=open(path+'/'+IpFileName)
    content=fd.read().split('\n')
    fd.close()
    iplist=[]
    for ip in content:
        if ip!='':
            iplist.append(ip)

    return iplist


def main():
       print 'starting at:',ctime()
       threads=[]
       iplist=getIpList()
       nloops=xrange(len(iplist))
       print iplist
       for i in nloops:
              t=threading.Thread(target=ThreadFunc(loop,(i,iplist[i]),loop.__name__))
              threads.append(t)
       for i in nloops:
              threads[i].start()
       for i in nloops:
              threads[i].join()
       print 'all done at:',ctime()
 
if __name__=='__main__':
       main()

(2)python 中需要处理的文本文件iplist如下:

[wln@localhost concurrence]$ cat iplist.txt 
10.40.127.1
10.40.127.2


10.40.127.3
10.40.127.4
10.40.127.5
10.40.127.6

(3)python程序中调用的shell脚本内容如下:

[wln@localhost concurrence]$ cat shell.sh 
echo $1

(4)执行python 程序结果如下:

[wln@localhost concurrence]$ python 07.py 
starting at: Mon Jul  7 03:05:41 2014
['10.40.127.1', '10.40.127.2', '10.40.127.3', '10.40.127.4', '10.40.127.5', '10.40.127.6']
10.40.127.3
10.40.127.2
10.40.127.4
10.40.127.5
10.40.127.6
10.40.127.1
all done at: Mon Jul  7 03:05:41 2014




参考:

(1)python学习笔记——多线程编程

(2)python多线程学习

(3) python的threading和multiprocessing模块初探

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值