问题描述
我在 Python 中遇到键盘输入问题.我试过 raw_input,它只被调用一次.但我想在每次用户按任意键时读取键盘输入.我该怎么做?感谢您的回答.
例如你有一个这样的 Python 代码:
file1.py
#!/bin/python……做点事……
并且在文档的某个位置您希望始终检查输入:
虽然为真:input = raw_input(">>>")...对输入做一些事情...
这将始终等待输入.您可以将无限循环作为一个单独的进程进行线程化,同时做其他事情,以便用户输入可以对您正在执行的任务产生影响.
如果您只想在按下某个键时才要求输入,并将其作为循环执行,请使用此代码(取自 Steven D'Aprano 的这个 ActiveState 配方)您可以等待按键发生,然后请求输入,执行任务并返回到之前的状态.
导入系统尝试:导入 tty,termios除了导入错误:# 可能是 Windows.尝试:导入msvcrt除了导入错误:# FIXME 在其他平台上做什么?#在这里放弃吧.引发导入错误('获取不可用')别的:getch = msvcrt.getch别的:定义获取():""getch() ->关键人物从 stdin 读取单个按键并返回结果字符.控制台没有回显任何内容.如果按键按下,此调用将被阻止尚未可用,但不会等待按下 Enter 键.如果按下的键是修改键,则不会检测到任何内容;如果它是一个特殊的功能键,它可能返回第一个字符转义序列,在缓冲区中留下额外的字符."fd = sys.stdin.fileno()old_settings = termios.tcgetattr(fd)尝试:tty.setraw(fd)ch = sys.stdin.read(1)最后:termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)返回通道
那么如何处理呢?好吧,现在每次您想等待按键时调用 getch()
即可.就像这样:
虽然为真:getch() # 这也返回按下的键,如果你想存储它input = raw_input(输入输入")do_whatever_with_it
您也可以同时执行其他任务.
请记住,Python 3.x 不再使用 raw_input,而是简单地使用 input().
I have problem with keyboard input in Python. I tried raw_input and it is called only once. But I want to read keyboard input every time user press any key. How can I do it? Thanks for answers.
So for instance you have a Python code like this:
file1.py
#!/bin/python
... do some stuff...
And at a certain point of the document you want to always check for input:
while True:
input = raw_input(">>>")
... do something with the input...
That will always wait for input. You can thread that infinite loop as a separate process and do other things in the meanwhile, so that the user input can have an effect in the tasks you are doing.
If you instead want to ask for input ONLY when a key is pressed, and do that as a loop, with this code (taken from this ActiveState recipe by Steven D'Aprano) you can wait for the key press to happen, and then ask for an input, execute a task and return back to the previous state.
So how to deal with this? Well, now just call getch()
every time you want to wait for a key press. Just like this:
while True:
getch() # this also returns the key pressed, if you want to store it
input = raw_input("Enter input")
do_whatever_with_it
You can also thread that and do other tasks in the meanwhile.
Remember that Python 3.x does no longer use raw_input, but instead simply input().
这篇关于如何在 Python 中读取键盘输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!