python 键盘输入指定键能够启动循环,如何退出Python程序或通过键绑定或宏循环?键盘中断不起作用...

I am trying to complete a simple GUI automation program that merely opens a web page and then clicks on a specific spot on the page every 0.2 seconds until I tell it to stop. I want my code to run and have its loop run infinitely until a keybind I specify breaks the loop (or entire program). I started out with the classic, KeyboardInterrupt, which enables CTRL+C to exit a program. Here is what I thought my final code would look like:

import webbrowser, pyautogui, time

webbrowser.open('https://example.com/')

print('Press Ctrl-C to quit.')

time.sleep(5)

#pyautogui.moveTo(1061, 881)

try:

while True:

time.sleep(0.2)

pyautogui.click(1061,881)

except KeyboardInterrupt:

print('\nDone.')

Everything about the code works, except the fact that I can't exit it once the clicking loop starts. Keyboard interrupt and using CTRL-C to exit do not work at all for this script, for whatever reason.

I merely want to be able to press "escape" (or any other key) to exit the loop (or the program altogether) - just any way to make the loop exit and stop. Right now it runs ad infinitum, but I want a simple keybind macro to be able to stop/break it.

I've tried using getch to keybind the escape key to cause a break, but to no avail:

import webbrowser, pyautogui, time, msvcrt

webbrowser.open('https://example.com')

print('Press Ctrl-C to quit.')

time.sleep(5)

#pyautogui.moveTo(1061, 881)

try:

while True:

time.sleep(0.2)

pyautogui.click(1061,881)

if msvcrt.kbhit():

key = ord(readch())

if key == 27:

break

I'm surprised it's been so hard to do this in Python. I've checked out a lot of similar problems across Stackoverflow, but with unsatisfactory answers, and none that solve my problem, unfortunately. I've been able to do things like this in simpler coding languages like AuotHotKeys with ease. I feel like I'm dancing around the solution. Any and all help would be wonderfully appreciated! Thanks in advance.

解决方案

If I understood correctly, you want to be able to stop your program by pressing a key on your keyboard.

To make you create a thread that will check in background if you press the key in question.

A little example:

import threading, time

from msvcrt import getch

key = "lol"

def thread1():

global key

lock = threading.Lock()

while True:

with lock:

key = getch()

threading.Thread(target = thread1).start() # start the background task

while True:

time.sleep(1)

if key == "the key choosen":

# break the loop or quit your program

Hope its help.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值