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.
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
In python2.x, simply use an infinite
while
loop with conditionalbreak
:So for instance you have a Python code like this:
file1.py
And at a certain point of the document you want to always check for 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: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().