(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
参考:
(2)python多线程学习