在Python中不断寻找用户输入
我将如何编写一个总是在寻找用户输入的Python程序。我想我希望有一个等于输入的变量,然后根据这个变量等于什么,会发生一些不同的事情。因此,如果变量是“w”,那么它将执行某个命令,并一直执行该命令,直到它收到另一个类似“d”的输入,然后会发生一些不同的情况,但它不会停止,直到您按下enter键 来自在Python中不断寻找用户输入,python,Python,我将如何编写一个总是在寻找用户输入的Python程序。我想我希望有一个等于输入的变量,然后根据这个变量等于什么,会发生一些不同的事情。因此,如果变量是“w”,那么它将执行某个命令,并一直执行该命令,直到它收到另一个类似“d”的输入,然后会发生一些不同的情况,但它不会停止,直到您按下enter键 来自 #/usr/bin/python #文件名:while.py 数字=23 运行=真 运行时: guess=int(输入('输入整数:')) 如果guess==数字: 打印('祝贺你,你猜对了') r
#/usr/bin/python
#文件名:while.py
数字=23
运行=真
运行时:
guess=int(输入('输入整数:'))
如果guess==数字:
打印('祝贺你,你猜对了')
running=False#这会导致while循环停止
elif guess<数字:
打印('不,比那个高一点。')
其他:
打印('不,比那个低一点')
其他:
打印('while循环结束')
#你还想在这里做什么
打印(‘完成’)
您也可以使用定义,例如:
def main():
(your main code)
main()
main()
虽然循环通常更干净,不需要全局变量:)可能就是您要寻找的,但它会检查文件描述符中是否有准备好读取的数据,因此您只能读取其中的数据,而无需中断处理(在本例中,它会等待一秒钟,但将该1替换为0,它将完美工作):
如果您想不断地查找所需的用户输入 例如:
import threading
import queue
def console(q):
while 1:
cmd = input('> ')
q.put(cmd)
if cmd == 'quit':
break
def action_foo():
print('--> action foo')
def action_bar():
print('--> action bar')
def invalid_input():
print('---> Unknown command')
def main():
cmd_actions = {'foo': action_foo, 'bar': action_bar}
cmd_queue = queue.Queue()
dj = threading.Thread(target=console, args=(cmd_queue,))
dj.start()
while 1:
cmd = cmd_queue.get()
if cmd == 'quit':
break
action = cmd_actions.get(cmd, invalid_input)
action()
main()
正如您将看到的,您的消息会有点混乱,例如:
> foo
> --> action foo
bar
> --> action bar
cat
> --> Unknown command
quit
这是因为有两个线程同时写入stdoutput。要同步它们,需要:
好了,现在更好了:
# press Enter
> foo
--> action foo
# press Enter
> bar
--> action bar
# press Enter
> cat
--> Unknown command
# press Enter
> quit
请注意,在键入命令以进入“输入模式”之前,您需要按Enter键。如果您想从用户处重复获取输入
x=1
while x==1:
inp = input('get me an input:')
基于inp,您可以执行任何条件。我不太清楚您想要实现什么,但是如果您需要很好地控制用户插入数据的方式,您可能需要GUI应用程序……不需要GUI应用程序,这是一个研究项目,而不是应用程序开发。因此,您试图说我可以使用基本的是的,这应该是一个很好的开始。也许可以解释一下
select
的作用是什么?我不明白为什么这被否决了。虽然不推荐,但它有效。为什么不“尽管正确”?
import threading
import queue
def console(q, lock):
while 1:
input() # Afther pressing Enter you'll be in "input mode"
with lock:
cmd = input('> ')
q.put(cmd)
if cmd == 'quit':
break
def action_foo(lock):
with lock:
print('--> action foo')
# other actions
def action_bar(lock):
with lock:
print('--> action bar')
def invalid_input(lock):
with lock:
print('--> Unknown command')
def main():
cmd_actions = {'foo': action_foo, 'bar': action_bar}
cmd_queue = queue.Queue()
stdout_lock = threading.Lock()
dj = threading.Thread(target=console, args=(cmd_queue, stdout_lock))
dj.start()
while 1:
cmd = cmd_queue.get()
if cmd == 'quit':
break
action = cmd_actions.get(cmd, invalid_input)
action(stdout_lock)
main()
# press Enter
> foo
--> action foo
# press Enter
> bar
--> action bar
# press Enter
> cat
--> Unknown command
# press Enter
> quit
x=1
while x==1:
inp = input('get me an input:')