python获取子进程返回值_python多线程获取子线程任务返回值

今天想实现多线程更新资产信息,所以使用到了threading,但是我需要每个线程的返回值,这就需要我在threading.Thread的基础上进行封装

def auto_asset(node):

ret = salt.remote_grains_execution_sigle(node)

asset_info={}

asset_info['os']= ret[node]['oscodename']

asset_info['kernelrelease']= ret[node]['kernelrelease']

asset_info['cpu_model']= ret[node]['cpu_model']

asset_info['dns']= ','.join(ret[node]['dns']['ip4_nameservers'])

asset_info['serialnumber'] = ret[node]['serialnumber']

asset_info['virtual'] = ret[node]['virtual']

asset_info['localhost'] = ret[node]['localhost']

asset_info['mem_total'] = ret[node]['mem_total']

asset_info['num_cpus'] = ret[node]['num_cpus']

asset_info['ip4_interfaces'] = " ".join(ret[node]['ip4_interfaces']['eth0'])

asset_info['hwaddr_interfaces'] = ret[node]['hwaddr_interfaces']['eth0']

return asset_info

import threading

class MyThread(threading.Thread):

def __init__(self,func,args=()):

super(MyThread,self).__init__()

self.func = func

self.args = args

def run(self):

self.result = self.func(*self.args)

def get_result(self):

try:

return self.result # 如果子线程不使用join方法,此处可能会报没有self.result的错误

except Exception:

return None

ass =Asset.objects.all()

ids_list =[ i.inner_ip for i in ass]

files = range(len(ids_list))

t_list = []

t_data = []

for i in files:

t = MyThread(auto_asset, (ids_list[i],))

t_list.append(t)

t.start()

for t in t_list:

t.join() # 一定要join,不然主线程比子线程跑的快,会拿不到结果

t_data.append(t.get_result())

print(t.get_result())

执行结果

{'localhost': 'VM_75_82_centos', 'hwaddr_interfaces': '52:54:00:95:fe:c8', 'disks': {'/dev/vda1': {'total': '49.09G', 'capacity': '17%', 'avail': '38.96', 'used': '7.63'}}, 'dns': '10.236.158.106,10.236.158.114', 'ip4_interfaces': '10.105.75.82', 'num_cpus': 1, 'serialnumber': 'a1dad25c-8e69-4838-a489-0fe1958e76df', 'os': 'CentOS Linux 7 (Core)', 'mem_total': 1839, 'cpu_model': 'Intel(R) Xeon(R) CPU E5-26xx v4', 'kernelrelease': '3.10.0-514.26.2.el7.x86_64', 'virtual': 'kvm'}

{'localhost': 'wordpress', 'hwaddr_interfaces': 'fa:16:3e:1a:49:72', 'disks': {'/dev/vda1': {'total': '29.99G', 'capacity': '12%', 'avail': '26.54', 'used': '3.45'}}, 'dns': '103.224.222.222,103.224.222.223,8.8.8.8', 'ip4_interfaces': '192.168.0.3', 'num_cpus': 1, 'serialnumber': 'c6bce500-113d-11e7-a010-0425c53afb57', 'os': 'CentOS Linux 7 (Core)', 'mem_total': 1839, 'cpu_model': 'Intel Core Processor (Broadwell, IBRS)', 'kernelrelease': '3.10.0-514.el7.x86_64', 'virtual': 'kvm'}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值