简体   繁体   中英

How to Return Value from a thread by via function that calls context manager?

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))

Output :

Interactive SSH session established
None
<class 'NoneType'>

I want to return the pod name and save it to a variable using threading. How can I use threading module to call a function find_bfs_pod_name and use its return value somewhere else?

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__)

This is the solution

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM