【问题标题】:How to do something till an input is detected in python3?在python3中检测到输入之前如何做某事?
【发布时间】:2020-12-24 11:48:37
【问题描述】:

我想在用户输入之前执行一段代码(检测到 随机 按键),我该如何在 Python 3.x 中执行此操作?

伪代码如下:

while input == False:
    print(x)

【问题讨论】:

  • 嗨,x 是什么?您期望用户提供哪种类型的输入?数字,字符串,只是按键?
  • @CarloZanocco 只是按键,x 只是一个任意值
  • 好的,用KeyboardInterrupt处理就行了
  • @CarloZanocco 键盘中断严格来说是ctrl+c,对吧?
  • @CarloZanocco 这就是我想要的,谢谢

标签: python python-3.x input user-input


【解决方案1】:

你可以这样做:

try:
    while True:
        print("Running")
except KeyboardInterrupt:
    print("User pressed CTRL+c. Program terminated.")

用户只需按 Control+c。

Python 提供了内置的异常KeyboardInterrupt 来处理这个问题。

使用pynput 任意随机按键来完成此操作

import threading
from pynput.keyboard import Key, Listener

class MyClass():
    def __init__(self) -> None:
        self.user_press = False

    def RandomPress(self, key):
        self.user_press = True

    def MainProgram(self):
        while self.user_press == False:
            print("Running")
        print("Key pressed, program stop.")

    def Run(self):
        t1 = threading.Thread(target=self.MainProgram)
        t1.start()

        # Collect events until released
        with Listener(on_press=self.RandomPress) as listener:
            listener.join()

MyClass().Run()

【讨论】:

    【解决方案2】:

    如果你想和用户互动,你可以按照以下方式:

    flag = input("please enter yes or no?")
    if flag == "no":
        print(x)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-20
      • 2013-03-03
      • 2023-03-31
      • 2021-10-27
      • 1970-01-01
      • 2014-04-25
      • 1970-01-01
      相关资源
      最近更新 更多