繁体   English   中英

如何在Python中读取键盘输入

[英]How can I read keyboard input in Python

我在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配方 ),您可以等待按键发生,然后询问对于输入,执行任务并返回到先前的状态。

 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,而只是输入()。

在python2.x中,只需使用带有条件break的无限while循环:

In [11]: while True:
    ...:     k = raw_input('> ')
    ...:     if k == 'q':
    ...:         break;
    ...:     #do-something


> test

> q

In [12]: 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM