fahrbach
fahrbach

Reputation: 236

Python 3 - How to input data without pressing <return> in OSX

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.

Upvotes: 1

Views: 8497

Answers (2)

LeSgHsW
LeSgHsW

Reputation: 1

You can use Turtle to do something like this:

import turtle
Sc = turtle.Screen()
Sc.setup(width=0, height=0)         #this hides turtle's windows
def a():                            #that's the function that you want to run when the key is pressed
    #code here
    Sc.listen()                         #this tells the program to listen 
    for a keypress
    Sc.onkey("#The key here", #the function call here) #this tells the program

What function to call when a certain key is pressed

# An example of pressing the key "w"
Sc.onkey("w", a)

Upvotes: 0

Lambda Fairy
Lambda Fairy

Reputation: 14676

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
import time

# 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)

Upvotes: 1

Related Questions