LtPinback
LtPinback

Reputation: 506

command CHOICE in DOS batch replacement/reproduction in python

I want to reproduce the behavior of the command CHOICE in DOS batch but with python.

raw_input requires the user to type whatever then press the ENTER/RETURN key. What I really want is for the user to press a single key and the script to continue from there.

Upvotes: 2

Views: 361

Answers (2)

z33m
z33m

Reputation: 6053

A small utility class to read single characters from standard input : http://code.activestate.com/recipes/134892-getch-like-unbuffered-character-reading-from-stdin/

Upvotes: 2

Brian R. Bondy
Brian R. Bondy

Reputation: 347566

For Unix, it uses sys, tty, termios modules.

import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)

For Windows, it uses msvcrt module.

import msvcrt
ch = msvcrt.getch()

Source

Upvotes: 3

Related Questions