gpt4 book ai didi

python - 等待用户输入时运行循环

转载 作者:行者123 更新时间:2023-12-01 07:11:46 26 4
gpt4 key购买 nike

我想在用户未输入任何内容时在脚本中运行循环。但是当他们输入一些内容时,我希望循环中断。

我当前遇到的问题是,当使用 input() 函数时,脚本将停止并等待输入,但我想在等待输入时运行脚本的另一部分用户输入。

我尝试使用 try:raw_input():

while True:
try:
print('SCAN BARCODE')
userInput= raw_input()
#doing something with input
except:
#run this while there is no input

这样,我发现 except: 中的任何内容都将始终运行,但即使有用户输入,它也不会运行 try: 。如果我将 raw_input() 更改为 input(),脚本只会在 input() 处等待,并且不会在 中运行任何内容除外:

如何实现我所追求的目标?

最佳答案

你可以使用Python线程:

from threading import Thread
import time

thread_running = True


def my_forever_while():
global thread_running

start_time = time.time()

# run this while there is no input
while thread_running:
time.sleep(0.1)

if time.time() - start_time >= 5:
start_time = time.time()
print('Another 5 seconds has passed')


def take_input():
user_input = input('Type user input: ')
# doing something with the input
print('The user input is: ', user_input)


if __name__ == '__main__':
t1 = Thread(target=my_forever_while)
t2 = Thread(target=take_input)

t1.start()
t2.start()

t2.join() # interpreter will wait until your process get completed or terminated
thread_running = False
print('The end')

在我的示例中,您有 2 个线程,第一个线程启动并执行代码,直到您收到用户的一些输入,线程 2 正在等待用户的一些输入。获得用户输入后,线程 1 和 2 将停止。

关于python - 等待用户输入时运行循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58179445/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com