不断地在Python中寻找用户输入

2024-04-24 15:44:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我该如何编写一个总是在寻找用户输入的Python程序呢。我想我会想要一个变量等于输入,然后根据这个变量的等式,会发生一些不同的事情。因此,如果变量是“w”,那么它将执行一个特定的命令并一直这样做,直到它收到另一个类似“d”的输入,然后会发生一些不同的事情,但它不会停止,直到您点击enter。


Tags: 用户命令程序事情enter我会等式
3条回答

来自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')

如果您想不断地查找用户输入,您将需要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。要同步它们,需要^{}

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

也许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)

相关问题 更多 >