#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    5
    Rep Power
    0

    While with responses to keyboard


    Hi all,

    I'm a rather inexperienced python programmer. I'm looking for some construct that will start an indefinite loop (eg. while True or something similar) and the program will respond to the keyboard events. Something rather simple: q - get out of the loop and quit, 1 - do something, 2 - do something.

    Code:
    def some_function:
        pass
    
    def other_function:
        pass
    
    
    my loop:
        if key == "1":
            some_function
        else if key == "2":
            other_function
    Thanking you all.

    etc.

    I think it is called event driven programming. I can't find anything relevant. It's all about Twisted which looks like has a lot of opponents. Could you recommend something? I don't need/want GUI and I'd like something different than "input" where you need to press enter after the user input.
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,900
    Rep Power
    481
    curses
    http://docs.python.org/3/library/curses.html
    should help. You'll want raw or cbreak mode.

    Remember the command
    stty sane
    or you could use the atexit module to register a cleanup function that restores normal terminal functionality.

    Comments on this post

    • xtd agrees : Useful post
    [code]Code tags[/code] are essential for python code and Makefiles!
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    5
    Rep Power
    0
    Thank you. That's exactly what I wanted.
  6. #4
  7. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    5
    Rep Power
    0
    One more question. I'm trying to get the centre of a window so that I can position, eg. a title right in the middle regardless of the size of my terminal window.

    Thank you
  8. #5
  9. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,900
    Rep Power
    481
    Code:
    >>> import curses
    >>> w = curses.initscr()
    >>> w.getbegyx()
    (0, 0)
    >>> w.getmaxyx()
    (24, 80)
    >>> w.addstr(12,38,'hi!')
    >>> w.refresh()
    [code]Code tags[/code] are essential for python code and Makefiles!
  10. #6
  11. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    5
    Rep Power
    0
    Originally Posted by b49P23TIvg
    Code:
    >>> import curses
    >>> w = curses.initscr()
    >>> w.getbegyx()
    (0, 0)
    >>> w.getmaxyx()
    (24, 80)
    >>> w.addstr(12,38,'hi!')
    >>> w.refresh()
    Excellent. Thank you.

IMN logo majestic logo threadwatch logo seochat tools logo