python:使用多線程同時執行多個函數


 

 

使用多線程同時執行多個函數

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM