首先說一下pyhton中的多線程,因為是直接調用底層的C庫,沒有自己的底層方法 ,所以不如其它語言,應該算是python中的一個缺陷吧。
在多線程中,要引入模塊threading,使用時,通過T1=threading.Thread(target=func,args=('arg1',''arg2)來建立一個線程的實例對象。使用T1.start()來啟動線程。
看一看具體的代碼:
1 #可以看到大致的流程,但其中的線程鎖,好像不起作用。主要是看一下守護線程的用法和JOIN的用法 。 2 3 import threading,time 4 lock=threading.Lock() 5 num=1 6 def run(): 7 lock.acquire()#線程鎖,對3.0以上版本無效。 8 global num 9 num=num*2 10 lock.release() 11 t_obj=[] 12 start_time=time.time() 13 for i in range(50): 14 t=threading.Thread(target=run) 15 #t.setDaemon(True) #設置這個線程為主線程的守護線程。 16 t.start() 17 t_obj.append(t) 18 for i in t_obj: 19 i.join() 20 print('num:',num) 21 #print ('done time is ',time.time()-start_time)
在線程知識中,有一個EVEVT比較實用。
#可以看到,這里的Event類似於一個全局變量,兩個值:True False
import threading,time event=threading.Event() def light(): count=0 event.set() while True: if count>3 and count <=5: event.clear() print('Red light') elif count>5: event.set() print('Green light') count=0 else: print ('runing....') count+=1 def car(name): while True: if event.is_set(): print('car %s is run.....'%name) else: print('car %s is wait.....'%name) event.wait() l1=threading.Thread(target=light,) l1.start() c1=threading.Thread(target=car,args='Weiz') c1.start() # event.wait()(等待標志被設置) event.set() (對標志進行設置 ) event.clear() I(清除標志的設置) event.is_set() (判斷是否設置標志) 四個方法。
另外,利用線程和隊列結合,有利於“高內聚、低耦合”的實現,提高效率。
''' 生產者消費者模式的PYTHON演示實現。主要知識點:隊列 以生產餃子、吃餃子為例''' import threading,queue,time# 線程 隊列 日期 q=queue.Queue(maxsize=10) #first in first out #q1=queue.LifoQueue(maxsize=10) last in first out # q2=queue.PriorityQueue(maxsize=10) 可以設置優先級 def product(): n=1 while True: q.put('餃子%s'%n) print('生產了餃子',n) time.sleep(0.2) n+=1 def consumer(name): while True: print("%s eating %s"%(name,q.get())) time.sleep(0.1) p=threading.Thread(target=product,) p.start() c=threading.Thread(target=consumer,args=('Jack',)) c.start() c1=threading.Thread(target=consumer,args=('Tom',)) c1.start()
除了以上知識外,還有一個paramiko 模塊,可以實現SSH的客戶端,利用多線程,可以實現對多台主機的批量管理,可以批量執行命令,批量發送文件。
代碼示例:執行指令。
1 import paramiko 2 # 創建SSH對象 3 ssh = paramiko.SSHClient() 4 # 允許連接不在know_hosts文件中的主機 5 6 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 7 # 連接服務器 8 ssh.connect(hostname='10.0.0.31', port=52113, username='root', password='123456') 9 # 執行命令 10 stdin, stdout, stderr = ssh.exec_command('df') 11 # 獲取命令結果 12 res,err = stdout.read(),stderr.read() 13 result = res if res else err 14 15 print(result.decode()) 16 17 # 關閉連接 18 ssh.close()
代碼示例:發送文件。
import paramiko transport = paramiko.Transport(('10.0.0.31', 52113)) transport.connect(username='root', password='123456') sftp = paramiko.SFTPClient.from_transport(transport) # 將file1 上傳至服務器 /tmp/sftp.put(file1, '/tmp') # 將file2 下載到本地 local_path sftp.get(file2_path, 'fromlinux.txt') transport.close()