簡體   English   中英

Python 3、如何同時運行兩個函數?

[英]In Python 3, how can I run two functions at the same time?

我有 2 個功能:一個讀取文本文件,另一個在按下某個鍵時更改該文本文件。 我需要我的代碼每隔幾秒打印一次文本文件,同時監視按鍵以更改文件。 這可能嗎?我該怎么做?

我試過這個,但它不起作用。

def read_file():
   color = open("color.txt", "r")
   current_color = color.read()
   color.close()
   if current_color == "green":
       print("GREEN")
   elif current_color == "blue":
       print("BLUE")
   time.sleep(5)

def listen_change():
   if keyboard.is_pressed('g'):
       f = open("color.txt", "w")
       f.write("green")
       f.close()
   elif keyboard.is_pressed('b'):
       f = open("color.txt", "w")
       f.write("blue")
       f.close()

編輯:這是我嘗試多線程的方式

from threading import Thread

if __name__ == '__main__':
    Thread(target=read_file()).start()
    Thread(target=listen_change()).start()

我有兩個功能:一個讀取文本文件,另一個在按下鍵時更改該文本文件。 我需要我的代碼每隔幾秒鍾打印一次文本文件,同時監視按鍵以更改文件。 這可能嗎?我該怎么做?

我試過這個,但它不起作用。

def read_file():
   color = open("color.txt", "r")
   current_color = color.read()
   color.close()
   if current_color == "green":
       print("GREEN")
   elif current_color == "blue":
       print("BLUE")
   time.sleep(5)

def listen_change():
   if keyboard.is_pressed('g'):
       f = open("color.txt", "w")
       f.write("green")
       f.close()
   elif keyboard.is_pressed('b'):
       f = open("color.txt", "w")
       f.write("blue")
       f.close()

編輯:這是我嘗試多線程的方式

from threading import Thread

if __name__ == '__main__':
    Thread(target=read_file()).start()
    Thread(target=listen_change()).start()

target參數必須是 function。您正在立即調用函數,而不是傳遞對 function 的引用。

函數需要循環。

使用join()等待線程退出。

使用鎖來防止同時讀取和寫入文件,這可能會在部分 state 中讀取文件。

import keyboard
from threading import Thread, Lock

mutex = Lock()

def read_file():
   while True:
       with mutex:
           with open("color.txt", "r") as color:
               current_color = color.read()
       if current_color == "green":
           print("GREEN")
       elif current_color == "blue":
           print("BLUE")
       time.sleep(5)

def listen_change():
   while True:
       if keyboard.is_pressed('g'):
           with mutex:
               with open("color.txt", "w"):
                   f.write("green")
       elif keyboard.is_pressed('b'):
           with mutex:
               with open("color.txt", "w"):
                   f.write("blue")

if __name__ == '__main__':
    t1 = Thread(target = read_file)
    t2 = Thread(target = listen_change)
    t1.start()
    t2.start()
    t1.join() # Don't exit while threads are running
    t2.join()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM