【问题标题】:Constantly looking for user input in Python在 Python 中不断寻找用户输入
【发布时间】:2012-02-02 01:42:10
【问题描述】:

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

【问题讨论】:

  • 我不完全理解您想要实现的目标,但如果您需要很好地控制用户如何插入数据,您可能需要一个 GUI 应用程序...
  • 不想要 GUI 应用程序,这是一个研究项目而不是应用程序开发。

标签: python


【解决方案1】:

如果您想不断寻找用户输入,您需要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

这是因为有两个线程同时写入标准输出。要同步它们,需要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 才能进入“输入模式”。

【讨论】:

    【解决方案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')
    

    【讨论】:

    • 所以你想说我可以使用这段代码的基础知识(就像它的两行一样)并对其进行改造,直到它达到我想要的效果?
    • 是的,应该是一个很好的起点。
    【解决方案3】:

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

    【讨论】:

    • 或许能解释一下select 的作用?
    【解决方案4】:

    你也可以使用定义,比如:

    def main():
        (your main code)
        main()
    main()
    

    虽然通常 while 循环更简洁,并且不需要全局变量 :)

    【讨论】:

    • 我不明白为什么这被否决了。虽然不推荐,但它可以工作。
    【解决方案5】:

    如果您想从用户那里重复获取输入;

    x=1
    while x==1:
        inp = input('get me an input:')
    

    并且基于 inp 你可以执行任何条件。

    【讨论】:

    • 为什么不“当真”?
    猜你喜欢
    • 1970-01-01
    • 2016-03-08
    • 1970-01-01
    • 2020-05-24
    • 2018-03-17
    • 2014-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多