python多进程(三种方法)
#!/usr/bin/env python # -*- coding:utf-8 -*- from multiprocessing import Pool import time def f(x): time.sleep(1) print x return x*x if __name__ == '__main__': p = Pool(5) print(p.map(f,range(10)))
##########################################
#!/usr/bin/env python
#-*- coding:utf-8 -*-
from multiprocessing import Pool
import time
def f(n):
print n*n
time.sleep(1)
return n*n
if __name__ == '__main__':
p = Pool(processes=5)
res_list = []
for i in range(10):
res = p.apply_async(f,[i,])
res_list.append(res)
for item in res_list:
print item.get()
from multiprocessing import Process import os def info(title): print title print 'module name:', __name__ if hasattr(os, 'getppid'): # only available on Unix print 'parent process:', os.getppid() print 'process id:', os.getpid() def f(name): info('function f') print 'hello', name if __name__ == '__main__': info('main line') p = Process(target=f, args=('bob',)) p.start() p.join()
#显示多进程之间不进行通信
#显示多进程之间不进行通信 from multiprocessing import Process def run(info_title,n): info_title.append(n) print info_title info_title = [] if __name__ == '__main__': for i in range(10): p = Process(target=run,args=(info_title,i)) p.start() ############显示结果为############ [1] [0] [4] [6] [8] [7] [2] [9] [5] [3]
6.使用paramiko模块 以及超线程模块,查询所有主机硬盘空间大小:
#!/usr/bin/env python #-*- coding:utf-8 -*- from multiprocessing import Process import paramiko def sshclient(ipaddr): private_key_path = '/root/.ssh/id_rsa' key = paramiko.RSAKey.from_private_key_file(private_key_path) ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ipaddr,port=22,username='root',pkey=key,timeout=10) stdin,stdout,stderr = ssh.exec_command('df') print stdout.read() ssh.close() if __name__ == '__main__': ip_list = ['192.168.20.21','192.168.20.151','192.168.20.152'] for i in ip_list: p = Process(target=sshclient,args=(i,)) p.start()