1

In Pascal I can execute this code to get a character from keyboard input:

uses crt;
var ch: char;
begin
    ch := '.';
    while ch <> '\' do
    begin
        ch := readkey;
        writeln( ch );
    end;
end;

Is there a similar one in Python? :)

famousgarkin
  • 13,687
  • 5
  • 58
  • 74
Coki
  • 11
  • 1
  • 2
  • 2
    http://stackoverflow.com/questions/510357/python-read-a-single-character-from-the-user – 6502 Jan 25 '11 at 21:49

4 Answers4

3
import sys    

def prog():    
    char = ""     
    while char != "/":    
        char = sys.stdin.read(1)    
        print char
prog()
retornam
  • 329
  • 1
  • 8
2

You could do it by running Tkinter in the background:

import Tkinter

def keyPress(event, tk):
    ch = event.char
    if ch == '\\':
        tk.destroy()
    else:
        print ch

if __name__ == '__main__':
    tk = Tkinter.Tk()
    tk.bind_all('<Key>', lambda event: keyPress(event, tk))
    tk.withdraw()
    tk.mainloop()

(Hacked from: http://www.daniweb.com/forums/post567365.html#post567365)

erbridge
  • 1,376
  • 12
  • 27
0

raw_input.

Then slice the first character.

PrettyPrincessKitty FS
  • 6,117
  • 5
  • 36
  • 51
  • 2
    `raw_input` and `input` read a whole line (i.e. wait for return key). –  Jan 25 '11 at 21:50
  • I didn't know how Pascal's readkey worked, I assumed it was return press. – PrettyPrincessKitty FS Jan 25 '11 at 21:51
  • I don't know Pascal either (at least not enough to know this), but functions that mention "char" usually do just that without waiting for a whole line. –  Jan 25 '11 at 21:52
0

You can't use CRT; I recommend you to import pygame instead.

9000
  • 39,899
  • 9
  • 66
  • 104