请求输入一次然后等待响应

Ask input once then wait for response

我完全是个新手,我对在循环工作时询问输入有疑问。 让我们假装我有一个简单的循环。

x = 1    
y = 1
while x == 1:
   y += 1
   print(y)

现在我希望用户输入停止此脚本,但前提是他键入取消并且循环应该 运行 而 python 正在等待输入。

正如我在评论中提到的,您可以使用 threading 模块中的线程实现 "running the loop while waiting for input"。

想法是让两个线程 运行 并行(即同时),每个线程都做自己的事情。第一个只会做一件事:等待输入。第二个将完成您本应放入循环中的工作,并且仅在每个循环开始时根据从第一个线程获得的信息检查它是否应该停止。

以下代码说明了这一点(注意这需要 python3):

from threading import Thread
import time


class Input_thread(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.keep_working = True

    def run(self):
        while True:
            a = input("Type *cancel* and press Enter at anytime to cancel \n")
            print("You typed "+a)
            if a == "cancel":
                self.keep_working = False
                return
            else:
                pass


class Work_thread(Thread):
    def __init__(self, other_thread):
        Thread.__init__(self)
        self.other_thread = other_thread

    def run(self):
        while True:
            if self.other_thread.keep_working is True:
                print("I'm working")
                time.sleep(2)
            else : 
                print("I'm done")
                return



# Creating threads
input_thread = Input_thread()
work_thread = Work_thread(input_thread)

# Lanching threads
input_thread.start()
work_thread.start()

# Waiting for threads to end
input_thread.join()
work_thread.join()

如您所见,使用 threading 并非易事,需要一些有关 类 的知识。

一种以稍微简单的方式实现类似功能的方法是使用 python 的异常 KeyboardInterrupt。如果您不熟悉异常:在您的代码中有 python 处理错误的方法,这意味着如果在您的代码中的某个点 Python 找到它不能 运行,它将引发异常,如果没有计划处理该错误(也就是如果您不捕获异常 try/except 语法),python 停止 运行ning 并在终端 window.

中显示该异常和回溯

现在的问题是,当您在终端 window 中按 Ctrl-c(与复制快捷方式相同)而您的程序 运行s 时,它会自动引发一个名为 KeyboardInterupt 在您的程序中,您可以捕获它以将其用作将 cancel 发送到您的程序的方式。 有关如何执行此操作的示例,请参阅该代码:

import time 

y=1
try:
    while True:
        y+=1
        print(y)
        time.sleep(1)

except KeyboardInterrupt:
    print("User pressed Ctrl-c, I will now exit gracefully")

print("Done")