我如何编写一个始终在寻找用户输入的Python程序。我想我想要一个等于输入的变量,然后根据变量等于的东西发生不同的事情。因此,如果变量是“w”,那么它将执行某个命令并继续这样做,直到它收到另一个输入,如“d”然后会发生不同的事情,但它不会停止,直到你点击输入。
答案 0 :(得分:4)
如果您想不断寻找用户输入,则需要multithreading。
示例:
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。要同步它们,需要lock
:
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
请注意,在输入命令进入“输入模式”之前,您需要按Enter
。
答案 1 :(得分:2)
来自http://www.swaroopch.com/notes/Python_en:Control_Flow
#!/usr/bin/python
# Filename: while.py
number = 23
running = True
while running:
guess = int(input('Enter an integer : '))
if guess == number:
print('Congratulations, you guessed it.')
running = False # this causes the while loop to stop
elif guess < number:
print('No, it is a little higher than that.')
else:
print('No, it is a little lower than that.')
else:
print('The while loop is over.')
# Do anything else you want to do here
print('Done')
答案 2 :(得分:1)
也许select.select正是您所寻找的,它检查是否有数据准备好在文件描述符中读取,因此您只能读取它无需中断处理的位置(在示例中它是等待一秒,但用0代替1,它将完美地工作:
import select
import sys
def times(f): # f: file descriptor
after = 0
while True:
changes = select.select([f], [], [], 1)
if f in changes[0]:
data = f.readline().strip()
if data == "q":
break
else:
print "After", after, "seconds you pressed", data
after += 1
times(sys.stdin)
答案 3 :(得分:0)
你也可以使用这样的定义:
def main():
(your main code)
main()
main()
虽然通常while循环更清晰,并且不需要全局变量:)
答案 4 :(得分:0)
如果你想从用户那里反复获取输入;
x=1
while x==1:
inp = input('get me an input:')
并且基于inp,您可以执行任何条件。