【问题标题】:How to create a command line interface that doesn't stop the program to wait for user input?如何创建一个不停止程序等待用户输入的命令行界面?
【发布时间】:2021-09-21 23:04:33
【问题描述】:

我正在用 python 编写一个程序,它要求程序在后台不断运行,用户可以随时键入以暂停或结束程序。

到目前为止,我只能让程序完全停止并等待用户输入内容。

uInput = ""

counter = 3

while uInput != "password" and counter >= 0:
    uInput = input

    if uInput != "password":
        print("Incorrect Password.", counter, "tries remaining.")
        counter -= 1

输入语句完全冻结程序,直到用户按下回车键。在等待用户输入内容时,是否可以让程序运行,例如计时器或只是另一个程序?任何教程或提示都会有所帮助。

【问题讨论】:

标签: python-3.x multithreading user-interface input while-loop


【解决方案1】:

为此使用时间模块和线程模块。 代码:

from threading import Thread
import time

uInput = ""

counter = 3

thread_running = True


def passwordInputting():
    global counter
    start_time = time.time()
    while time.time() - start_time <= 10:
        uInput = input()
        if uInput != "password":
            print("Incorrect Password.", counter, "tries remaining.")
            counter -= 1
                                
        else:
            # code for if password is correct
            break

def passwordTimer():

    global thread_running
    global counter

    start_time = time.time()

    # run this while there is no input or user is inputting
    while thread_running:
        time.sleep(0.1)
        if time.time() - start_time >= 10:
            if uInput == "password":
                continue
            else:
                if counter > 0:
                    print("Incorrect Password.", counter, "tries remaining.")
                    counter -= 1
                    start_time = time.time() + 10
                    
                else:
                    # code for when no more tries left
                    break
                
timerThread = Thread(target=passwordTimer)
inputThread = Thread(target=passwordInputting)

timerThread.start()
inputThread.start()

inputThread.join() # interpreter will wait until your process get completed or terminated
thread_running = False

如果您想了解更多关于线程自己的信息,请看这里:https://realpython.com/intro-to-python-threading/

【讨论】:

  • 当您输入错误的密码时,它会显示“UnboundLocalError: local variable 'counter' referenced before assignment'
  • @ChristopherOjo 抱歉,现在应该可以使用了
  • 你能解释一下你做了什么改变吗?只是全局变量计数器吗?
  • @ChristopherOjo 是的,发生 unboundlocalerror 是因为 counter 被视为局部变量而不是全局变量。 global counter 解决了这个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多