在Python中不断寻求用户输入
我想写一个Python程序,让它一直在等待用户输入。我想先把用户输入的内容存储到一个变量里,然后根据这个变量的值来执行不同的操作。比如,如果这个变量的值是“w”,程序就会执行某个特定的命令,并且会一直执行这个命令,直到用户输入了其他的内容,比如“d”。这时程序会执行不同的操作,但它不会停止,直到你按下回车键。
5 个回答
1
也许你在找的就是 select.select 这个东西。它的作用是检查一个文件描述符里是否有数据可以读取,这样你就可以只在有数据的时候去读取,避免了需要中断正在进行的处理(在这个例子里,它会等一秒钟,但如果把那个1换成0,它就会完美运行):
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)
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')
6
如果你想要持续不断地等待用户输入,你就需要用到多线程。
举个例子:
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
这是因为有两个线程同时在往标准输出写东西。为了让它们同步,你需要用到锁
:
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
键,然后再输入命令,这样才能进入“输入模式”。