【发布时间】:2022-01-04 03:30:19
【问题描述】:
在构建可以切换为垃圾邮件的脚本时。我遇到了以下问题。 首先是脚本的正常运行版本:
import keyboard
import threading
def spam_this():
status = 0
while True:
if keyboard.is_pressed("F9") and status == 0:
status = 1
event.wait(1)
if keyboard.is_pressed("F9") and status == 1:
status = 0
event.wait(1)
while status == 1:
if keyboard.is_pressed("F9") and status == 1:
status = 0
event.wait(1)
print("test")
event = threading.Event()
threading.Thread(target=spam_this).start()
上面的脚本完美运行。但是,当我将print("test") 更改为keyboard.write("test") 时。脚本中断。
import keyboard
import threading
def spam_this():
status = 0
while True:
if keyboard.is_pressed("F9") and status == 0:
status = 1
event.wait(1)
if keyboard.is_pressed("F9") and status == 1:
status = 0
event.wait(1)
while status == 1:
if keyboard.is_pressed("F9") and status == 1:
status = 0
event.wait(1)
keyboard.write("test")
event = threading.Event()
threading.Thread(target=spam_this).start()
这个版本的带有keyboard.write() 功能的脚本可以使用隐含的切换键“F9”来启动,但是当我尝试通过再次按“F9”来关闭开关时,它不会像@987654326 那样停止@自己的版本。
注意:我不知道如何在标题中描述这个问题。我使用术语“阻塞”是因为其效果类似于 time.sleep() 之类的阻塞方法在尝试创建带有切换的 while True: 循环时所做的。
【问题讨论】:
-
如果您在
while status == 1中运行代码,那么您不必检查and status == 1 -
如果你使用
True/False而不是0/1,那么你可以使用status = not status并且在while之前只使用一个if(没有and status == ...)`。
标签: python multithreading keyboard