[英]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.