[Linux] Detect a key press

J

Jia,Lu

Hi all
I write a program to detect key press,but , why there is a *space*
before the character I typed.??

#!/usr/bin/env python

import sys
import tty
import termios

i = sys.stdin.fileno()
o = sys.stdout.fileno()

backup = termios.tcgetattr(i)

def loop():
while 1:
ch = sys.stdin.read(1)
print "->%s"%ch
if ch == 'q':break

try:
tty.setraw(i)
loop()
finally:
termios.tcsetattr(i, termios.TCSADRAIN, backup)
 
S

Sergei Organov

Jia said:
Hi all
I write a program to detect key press,but , why there is a *space*
before the character I typed.??

There is none. The output I see when I type 1 2 q is:

->1
->2
->q

If that is what you see, the problem is in your

print "->%s"%ch

statement. It implicitly outputs '\n' at the end, and when terminal is
set in raw mode, this is not translated into '\r\n' as when terminal is
in canonical mode.

Try

print "->%s\r" % ch

or just

sys.stdout.write(ch)

-- Sergei.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,189
Latest member
CryptoTaxSoftware

Latest Threads

Top