如何通过调用上下文管理器的函数从线程返回值?

时间:2019-12-21 10:35:11

标签: python multithreading

import netmiko as net_manager
import time,threading,multiprocessing,concurrent.futures,queue
from contextlib import contextmanager

class Utilities:

    @staticmethod
    @contextmanager
    def makeconnection(ip,username,password):
        try:
            conn = net_manager.ConnectHandler(ip=ip, username=username, password=password, secret='ENABLE',verbose=True,device_type='linux')
            yield conn
        finally:
            conn.disconnect()


def find_bfs_pod_name():
    util = Utilities()
    with util.makeconnection(keywords.ip,keywords.username,keywords.password) as newconnection:
        bfs_pod_name = newconnection.send_command('sudo kubectl get pods | grep bfs | awk '{print $1}' | head -n 1')
    return bfs_pod_name

t1 = threading.Thread(target=find_bfs_pod_name)
t1.start()
result = t1.join()
print(result)
print(type(result))

输出:

Interactive SSH session established
None
<class 'NoneType'>

我想返回容器名称,并使用线程将其保存到变量中。 如何使用线程模块调用函数find_bfs_pod_name并在其他地方使用其返回值?

1 个答案:

答案 0 :(得分:0)

with concurrent.futures.ThreadPoolExecutor() as executor:
    #Creating Bfs Pod Name Thread
    bfs_pod_thread = executor.submit(find_bfs_pod_name)
    print(bfs_pod_thread.__dict__)
    bfs_pod_name = bfs_pod_thread.result()
    print(bfs_pod_name)
    print(bfs_pod_thread.__dict__)
    #Creating System Status Thread
    system_status = executor.submit(get_system_status)
    print(system_status.__dict__)
    systemstatus = system_status.result()
    print(systemstatus)
    status,reason = systemstatus
    print(status)
    print(reason)
    print(get_system_status.__dict__)

这是解决方案