如何在Python中读取键盘输入

2024-03-24

我在 Python 中遇到键盘输入问题。我尝试了 raw_input 并且它只被调用一次。但我想在用户每次按任意键时读取键盘输入。我该怎么做?感谢您的回答。


例如,你有这样的 Python 代码:

file1.py

#!/bin/python
... do some stuff...

在文档的某个特定点,您希望始终检查输入:

while True:
    input = raw_input(">>>")
    ... do something with the input...

这将始终等待输入。您可以将该无限循环作为一个单独的进程进行线程化,同时执行其他操作,以便用户输入可以对您正在执行的任务产生影响。

如果您只想在按下某个键时要求输入,并使用此代码(取自Steven D'Aprano 的 ActiveState 配方 http://code.activestate.com/recipes/577977-get-single-keypress/)您可以等待按键发生,然后请求输入,执行任务并返回到之前的状态。

import sys

try:
    import tty, termios
except ImportError:
    # Probably Windows.
    try:
        import msvcrt
    except ImportError:
        # FIXME what to do on other platforms?
        # Just give up here.
        raise ImportError('getch not available')
    else:
        getch = msvcrt.getch
else:
    def getch():
        """getch() -> key character

        Read a single keypress from stdin and return the resulting character. 
        Nothing is echoed to the console. This call will block if a keypress 
        is not already available, but will not wait for Enter to be pressed. 

        If the pressed key was a modifier key, nothing will be detected; if
        it were a special function key, it may return the first character of
        of an escape sequence, leaving additional characters in the buffer.
        """
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(fd)
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch

那么如何处理这个问题呢?好吧,现在只要打电话getch()每次你想等待按键时。像这样:

while True:
    getch() # this also returns the key pressed, if you want to store it
    input = raw_input("Enter input")
    do_whatever_with_it

您还可以线程化它并同时执行其他任务。

请记住,Python 3.x 不再使用 raw_input,而是简单地使用 input()。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在Python中读取键盘输入 的相关文章

随机推荐