[Linux] Detect a key press

Discussion in 'Python' started by Jia,Lu, Oct 6, 2006.

  1. Jia,Lu

    Jia,Lu Guest

    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)
    Jia,Lu, Oct 6, 2006
    #1
    1. Advertising

  2. Jia,Lu

    hanumizzle Guest

    On 5 Oct 2006 21:45:47 -0700, Jia,Lu <> wrote:
    > Hi all
    > I write a program to detect key press,but , why there is a *space*
    > before the character I typed.??


    Puzzles me too, but I know this is really easy in Curses (on top of
    that, it isn't specific to Linux; curses works on many terminals)

    http://www.amk.ca/python/howto/curses/

    -- Theerasak
    hanumizzle, Oct 6, 2006
    #2
    1. Advertising

  3. "Jia,Lu" <> writes:

    > 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.
    Sergei Organov, Oct 6, 2006
    #3
  4. Jia,Lu

    hanumizzle Guest

    On 10/6/06, Sergei Organov <> wrote:

    > Try
    >
    > print "->%s\r" % ch
    >
    > or just
    >
    > sys.stdout.write(ch)


    Ah!
    hanumizzle, Oct 7, 2006
    #4
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. James

    DataGrid key press question

    James, Jun 29, 2004, in forum: ASP .Net
    Replies:
    0
    Views:
    592
    James
    Jun 29, 2004
  2. Natty Gur
    Replies:
    0
    Views:
    577
    Natty Gur
    Jun 30, 2003
  3. Tracey

    Return Key Press

    Tracey, Dec 15, 2003, in forum: ASP .Net
    Replies:
    1
    Views:
    413
    Steve C. Orr [MVP, MCSD]
    Dec 15, 2003
  4. Replies:
    0
    Views:
    462
  5. Krist
    Replies:
    24
    Views:
    391
    Thomas 'PointedEars' Lahn
    Dec 15, 2009
Loading...

Share This Page