[英]Connect to multiple machines with threading in Python
我需要连接到多台计算机并在它们上执行命令集。 我想用线程来实现这一点,但不确定如何实现。 以下是代码:
import threading
def conn_to_board(board_ip):
# ssh connection to machine
# set of commands
board_ip = ["1.1.1.1", "2.2.2.2", "3.3.3.3", "4.4.4.4"]
'''
for i in board_ip:
t1 = threading.Thread(target=conn_to_board, args=(i,))
t1.start()
t1.join()
'''
有人可以通过线程帮助我实现这一目标吗?
假设函数conn_to_board(board_ip)
已经满足您的要求,并且没有绑定相同的本地端口,或者独占使用资源,那么多线程很简单,并且您的代码几乎是正确的。 我在注释代码中看到的唯一问题是,您实际上将循环中的每个线程都一个接一个地序列化地加入了循环中-换句话说,多线程在这里是完全没有用的。
您应该首先创建并启动所有线程(如果数量足够少),然后将它们加入新的循环中:
...
thrs = [] # to store the threads
for i in board_ip: # create and start the threads
t1 = threading.Thread(target=conn_to_board, args=(i,))
t1.start()
thrs.append(t1)
for t1 in thrs: # join all the threads
t1.join()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.