使用多線程同時執行多個函數
import time import os import threading def open_calc(): with open('test.txt', 'r') as f: for line in f.readlines(): while 'hello' in line: os.system("calc.exe") # 如果字符串已經出現並已經執行命令,則終止程序,否則會一直執行命令 return # 等for循環判斷完沒有標識后再休眠重新調用該函數 print('沒有找到啟動標識:hello,等5秒再檢測') time.sleep(5) # 再次調用函數 open_calc() def open_mstsc(): with open('test.txt', 'r') as f: for line in f.readlines(): while 'abc' in line: os.system("mstsc.exe") # 如果字符串已經出現並已經執行命令,則終止程序,否則會一直執行命令 return # 等for循環判斷完沒有標識后再休眠重新調用該函數 print('沒有找到啟動標識:abc,等6秒再檢測') time.sleep(6) # 再次調用函數 open_mstsc() if __name__ == '__main__': # 使用threading模塊,threading.Thread()創建線程,其中target參數值為需要調用的方法,同樣將其他多個線程放在一個列表中,遍歷這個列表就能同時執行里面的函數了 threads = [threading.Thread(target=open_calc), threading.Thread(target=open_mstsc)] for t in threads: # 啟動線程 t.start()