Python read stdin continually and effectively -
i'm trying design game in terminal in python2.7. in game class have this:
from board import board sys import stdin termios import tcgetattr getat, tcsetattr setat, tcsadrain tty import setraw class game: def __init__(self, **kwargs): self.board = board() # p1, p2 self.fd = stdin.fileno() self.old_settings = getat(self.fd) self.buffer = kwargs.get("key buffer", 4) if type(self.buffer) not int or self.buffer < 4: self.buffer = 4 def wait(self): keys = bytearray() while true: setraw(self.fd) keys.insert(0,stdin.read(1)) setat(self.fd, tcsadrain, self.old_settings) #'h'=104, 'j'=106, 'k'=107, 'l'=108, 'd'=100, '\x1b'=27, '['=91 if keys[0] == 104 or keys[0] == 68 , keys[2] == 27 , keys[1] == 91: print "left" elif keys[0] == 106 or keys[0] == 66 , keys[2] == 27 , keys[1] == 91: print "down" elif keys[0] == 107 or keys[0] == 65 , keys[2] == 27 , keys[1] == 91: print "up" elif keys[0] == 108 or keys[0] == 67 , keys[2] == 27 , keys[1] == 91: print "right" elif keys[0] == 3: break else: print repr(keys[0])
i threw quickly, , it's not much, makes stdin "raw" until receives char , flips doesn't mess stuff (found here). problem there lot of things aren't 1 character. illustration up-arrow key in decimal 27,91,65 or in hexadecimal 0x1b,0x5b,0x41 or bytes "\x1b\x5b\x41". 3 different bytes/chars. if @ code above can see partially around this, take lot of energy if wanted figure out if user pressed [home]
key, 4 bytes. harder still (actually appears impossible decipher if arrow key pressed or not), user have nail [esc]
(27 or 0x1b or "\x1b") [
(91 or 0x5b or "\x5b") , a
(65 or 0x41 or "\x41"). true of other arrow keys, of function keys [home]
, [pg up]
, [pg dn]
, [end]
, etc. keys, well. (i have tested hitting [esc]
, [
, a
, , works - i.e. interprets up
).
almost can read arrow keys, function keys, home/end/pg keys, why shouldn't able well? wasn't developed in python(2)? hoping can provide either improve way or read stdin or improve way of interpreting it.
python-2.x
No comments:
Post a Comment