不断寻找Python中的用户输入

cbb*_*ail 2 python

我将如何编写一个始终在寻找用户输入的Python程序。我想我想要一个等于输入的变量,然后根据该变量等于什么发生一些不同的事情。因此,如果变量为“ w”,则它将执行某个命令,并继续执行该命令,直到收到诸如“ d”之类的另一个输入为止。然后会发生一些不同的事情,但是直到您按下Enter键,它才会停止。

Rik*_*ggi 5

如果您要不断寻找用户输入,则需要多线程

例:

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()
Run Code Online (Sandbox Code Playgroud)

如您所见,这会使您的消息有些混乱,例如:

> foo
> --> action foo
bar
> --> action bar
cat
> --> Unknown command
quit
Run Code Online (Sandbox Code Playgroud)

这是因为有两个线程同时写入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()
Run Code Online (Sandbox Code Playgroud)

好吧,现在更好了:

    # press Enter
> foo
--> action foo
    # press Enter
> bar
--> action bar
    # press Enter
> cat
--> Unknown command
    # press Enter
> quit
Run Code Online (Sandbox Code Playgroud)

请注意,Enter在键入命令以进入“输入模式”之前,您需要先按。