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