Python 3 - How to input data without pressing

2019-01-27 11:31发布

问题:

I am attempting to move a character using the "asdw" keys in a game, but I cannot find a way to constantly input data without pressing return. I have seen that on windows there is a module called msvcrt, which has a getch function, so I am wondering if there is a way to simulate this in OSX, or more simply to just constantly input data from the keyboard.

回答1:

Try the curses library:

http://docs.python.org/py3k/library/curses.html

Curses is a library for controlling the terminal, and includes features such as drawing box shapes as well. It's available on any POSIX-compatible system, which includes Mac OS X and GNU/Linux.

Here's an example:

import curses

# Turn off line buffering
curses.cbreak()

# Initialize the terminal
win = curses.initscr()

# Make getch() non-blocking
win.nodelay(True)

while True:
    key = win.getch()
    if key != -1:
        print('Pressed key', key)
    time.sleep(0.01)