【问题标题】:In Python 3, how can I run two functions at the same time?在 Python 3 中,如何同时运行两个函数?
【发布时间】:2021-01-12 04:43:35
【问题描述】:

我有两个功能:一个读取文本文件,另一个在按键时更改该文本文件。我需要我的代码每隔几秒钟打印一次文本文件,同时监视按键以更改文件。这可能吗?我该怎么做?

我试过this,但是没用。

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

【问题讨论】:

  • 展示你对多线程的尝试。
  • @Barmar 我已经添加了,谢谢你的提问 :)
  • 目标参数应该是一个函数,而不是对该函数的调用。删除()
  • 您在链接的问题中没有看到吗?
  • 你只运行一次,而不是循环。

标签: python python-3.x multithreading function


【解决方案1】:

target 参数必须是一个函数。您是立即调用函数,而不是传递对函数的引用。

函数需要循环。

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

使用锁来防止同时读写文件,这可能会读取部分状态的文件。

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

【讨论】:

    猜你喜欢
    • 2021-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-19
    • 1970-01-01
    • 1970-01-01
    • 2021-08-13
    • 2020-09-01
    相关资源
    最近更新 更多