微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

按下某个键时暂停程序

如何解决按下某个键时暂停程序

嗨,我有一个向人们发送垃圾邮件的程序,但它可能会失控,因为我无法轻松暂停我的程序。

我需要在按下 \ 键时暂停编程的帮助吗?

import pyautogui
import time


numLines = 1
finished = False

while True:
    if finished == True:
        playAgain = input('Would you like to run this program again? ')
        if playAgain == 'no' or playAgain == 'No':
            break
        elif playAgain == 'Yes' or playAgain == 'yes':
            print('Have fun :)')
        else:
            print('Please try again - Invalid input')
    while True:
        whichScript = input('Please enter the name of the script you want to view: ')
        linesOrSend = input('Do you want to see the numer of lines or send: ')
        if linesOrSend == 'send' or linesOrSend == 'Send':
            time.sleep(5)
            check = input('Are you sure? ')
            if check == 'yes' or check == 'Yes':
                time.sleep(10)
                f = open(whichScript,"r")
                for word in f:
                    pyautogui.typewrite(word)
                    pyautogui.press('enter')
                finished = True
                break
            else:
                break
        elif linesOrSend == 'Lines' or linesOrSend == 'lines':
            f = open(whichScript,"r")
            for word in f:
                numLines += 1
            print(numLines)
            finished = True
            break
        else:
            print('Please try again - Invalid input')

解决方法

Python 有一个具有许多功能的键盘模块。安装它,也许使用以下命令:

pip3 install keyboard

然后在代码中使用它:

import keyboard  # using module keyboard
while True:  # making a loop
    try:  # used try so that if user pressed other than the given key error will not be shown
        if keyboard.is_pressed('q'):  # if key 'q' is pressed 
            print('You Pressed A Key!')
            break  # finishing the loop
    except:
        break  # if user pressed a key other than the given key the loop will break

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。