concurrent
Posted billhsu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了concurrent相关的知识,希望对你有一定的参考价值。
#--coding:utf-8--
import os,sys
def excutecmd(cmd):
print(‘cmd:::{}‘.format(cmd))
try:
print(‘1command is {} and pid is {}‘.format(cmd, os.getpid()))
ret = os.system(cmd)
print(‘2command is {} and pid is {}‘.format(cmd,os.getpid()))
if ret ==0:
# os._exit(0)
# print(‘ccc‘)
return ret
else:
# os._exit(1)
# print(‘bbb‘)
return ret
except Exception as e:
# os._exit(2)
# print(‘aaa‘)
return e
def multithreadExcute(cmdlist = [],defaultprocessnum = 3):
result = []
from concurrent import futures
with futures.ThreadPoolExecutor(max_workers=defaultprocessnum) as excutor:
for cmd in cmdlist:
ret = excutor.submit(excutecmd,cmd)
result.append(ret.result())
return result
def printline(result):
print(‘printline::{}‘.format(result))
pass
def multiprocessExcute(cmdlist = [],defaultprocessnum = 2):
result = []
import multiprocessing
pool = multiprocessing.Pool(processes=2)
for cmd in cmdlist:
ret = pool.apply_async(func=excutecmd,args=(cmd,),callback=printline,error_callback=printline)
result.append(ret)
pool.close()
pool.join()
return [i.get() for i in result]
if __name__ == ‘__main__‘:
cmdlist = [‘ping www.ifeng.com‘,‘ping www.google.com‘,‘ping www.huawei.com‘]
ret = multiprocessExcute(cmdlist)
print(ret)
print(‘done!‘)
以上是关于concurrent的主要内容,如果未能解决你的问题,请参考以下文章