Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #11017 > unrolled thread

Wait for a keypress before continuing?

Started byJohn Doe <jdoe@usenetlove.invalid>
First post2011-08-08 00:04 +0000
Last post2011-08-17 23:10 +0100
Articles 13 on this page of 33 — 13 participants

Back to article view | Back to comp.lang.python


Contents

  Wait for a keypress before continuing? John Doe <jdoe@usenetlove.invalid> - 2011-08-08 00:04 +0000
    Re: Wait for a keypress before continuing? Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2011-08-08 10:27 +1000
      Re: Wait for a keypress before continuing? John Doe <jdoe@usenetlove.invalid> - 2011-08-08 02:44 +0000
        Re: Wait for a keypress before continuing? Gelonida N <gelonida@gmail.com> - 2011-08-08 09:41 +0200
    Re: Wait for a keypress before continuing? John Doe <jdoe@usenetlove.invalid> - 2011-08-16 18:42 +0000
      Re: Wait for a keypress before continuing? John Doe <jdoe@usenetlove.invalid> - 2011-08-16 18:48 +0000
    Re: Wait for a keypress before continuing? John Doe <jdoe@usenetlove.invalid> - 2011-08-16 20:16 +0000
      Re: Wait for a keypress before continuing? Tim Roberts <timr@probo.com> - 2011-08-16 14:50 -0700
        Re: Wait for a keypress before continuing? John Doe <jdoe@usenetlove.invalid> - 2011-08-16 21:59 +0000
          Re: Wait for a keypress before continuing? Jerry Hill <malaclypse2@gmail.com> - 2011-08-16 20:11 -0400
            Re: Wait for a keypress before continuing? John Doe <jdoe@usenetlove.invalid> - 2011-08-17 03:52 +0000
              Re: Wait for a keypress before continuing? Seebs <usenet-nospam@seebs.net> - 2011-08-17 05:06 +0000
                Re: Wait for a keypress before continuing? John Doe <jdoe@usenetlove.invalid> - 2011-08-17 05:49 +0000
                  Re: Wait for a keypress before continuing? Seebs <usenet-nospam@seebs.net> - 2011-08-17 06:12 +0000
                    Re: Wait for a keypress before continuing? Chris Angelico <rosuav@gmail.com> - 2011-08-17 08:19 +0100
                    Re: Wait for a keypress before continuing? John Doe <jdoe@usenetlove.invalid> - 2011-08-17 07:23 +0000
                      Re: Wait for a keypress before continuing? Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2011-08-17 18:28 +1000
                        Re: Wait for a keypress before continuing? Seebs <usenet-nospam@seebs.net> - 2011-08-17 16:33 +0000
                          Re: Wait for a keypress before continuing? Ethan Furman <ethan@stoneleaf.us> - 2011-08-17 10:37 -0700
                      Re: Wait for a keypress before continuing? Ethan Furman <ethan@stoneleaf.us> - 2011-08-17 06:21 -0700
          Re: Wait for a keypress before continuing? Tim Roberts <timr@probo.com> - 2011-08-21 19:02 -0700
    Re: Wait for a keypress before continuing? John Doe <jdoe@usenetlove.invalid> - 2011-08-16 23:46 +0000
    Re: Wait for a keypress before continuing? peter <peter.mosley@talk21.com> - 2011-08-17 01:03 -0700
      Re: Wait for a keypress before continuing? Hans Mulder <hansmu@xs4all.nl> - 2011-08-17 16:16 +0200
        Re: Wait for a keypress before continuing? Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2011-08-18 02:36 +1000
        Re: Wait for a keypress before continuing? peter <peter.mosley@talk21.com> - 2011-08-18 01:24 -0700
          Re: Wait for a keypress before continuing? Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2011-08-18 09:50 -0700
          Re: Wait for a keypress before continuing? Nobody <nobody@nowhere.com> - 2011-08-18 18:58 +0100
      Re: Wait for a keypress before continuing? Seebs <usenet-nospam@seebs.net> - 2011-08-17 16:33 +0000
        Re: Wait for a keypress before continuing? Terry Reedy <tjreedy@udel.edu> - 2011-08-17 13:02 -0400
          Re: Wait for a keypress before continuing? Seebs <usenet-nospam@seebs.net> - 2011-08-17 17:05 +0000
          Re: Wait for a keypress before continuing? Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2011-08-18 04:29 +1000
            Re: Wait for a keypress before continuing? Chris Angelico <rosuav@gmail.com> - 2011-08-17 23:10 +0100

Page 2 of 2 — ← Prev page 1 [2]


#11982

FromTim Roberts <timr@probo.com>
Date2011-08-21 19:02 -0700
Message-ID<2vd357poedkl0icmu8m1dsmfq6aalujnpq@4ax.com>
In reply to#11618
John Doe <jdoe@usenetlove.invalid> wrote:
>
>Tim Roberts <timr probo.com> wrote: 
>
>> That exact code works perfectly for me.  The function returns as
>> soon as I press the escape key.  You are running this from a
>> console process, and not a GUI process, right? 
>
>No. I am running this from within Windows, all sorts of Windows. 
>
>So... Does that mean I will need something complex like a keyboard
>hook? Or what? 

I see that this conversation took a nasty turn while I was on vacation.

msvcrt.getch works with consoles.  If you have an application where stdin
and stdout are connected to a real, live console window (which looks just
like a command line window), then msvcrt.getch will work.  If not, then you
have to use the Windows APIs.  GetKeyboardState and GetKeyState can tell
you if a specific key is currently being pressed.
-- 
Tim Roberts, timr@probo.com
Providenza & Boekelheide, Inc.

[toc] | [prev] | [next] | [standalone]


#11624

FromJohn Doe <jdoe@usenetlove.invalid>
Date2011-08-16 23:46 +0000
Message-ID<4e4b0168$0$26208$c3e8da3$c14f6927@news.astraweb.com>
In reply to#11017
Okay... Looks like I need pyHook.

[toc] | [prev] | [next] | [standalone]


#11664

Frompeter <peter.mosley@talk21.com>
Date2011-08-17 01:03 -0700
Message-ID<2670f4ee-0ab4-42ba-a472-42a4c7669ce8@p5g2000vbl.googlegroups.com>
In reply to#11017
Is there an equivalent to msvcrt for Linux users?  I haven't found
one, and have resorted to some very clumsy code which turns off
keyboard excho then reads stdin. Seems such an obvious thing to want
to do I am surprised there is not a standard library module for it. Or
have I missed someting (wouldn't be the first time!)

Peter

[toc] | [prev] | [next] | [standalone]


#11686

FromHans Mulder <hansmu@xs4all.nl>
Date2011-08-17 16:16 +0200
Message-ID<4e4bcd37$0$23918$e4fe514c@news2.news.xs4all.nl>
In reply to#11664
On 17/08/11 10:03:00, peter wrote:
> Is there an equivalent to msvcrt for Linux users?  I haven't found
> one, and have resorted to some very clumsy code which turns off
> keyboard excho then reads stdin. Seems such an obvious thing to want
> to do I am surprised there is not a standard library module for it. Or
> have I missed someting (wouldn't be the first time!)

The quick and dirty way is to invoke stty(1) using os.system:

import os

def getpassword(prompt="Password: "):
     try:
         os.system("stty -echo")
         passwd = raw_input(prompt)
     finally:
         os.system("stty echo")
     return passwd


Strictly speaking, os.system is deprecated and you should use
the equivalent invocation of subprocess.call:

import subprocess

def getpassword(prompt="Password: "):
     try:
         subprocess.call(["stty", "-echo"])
         passwd = raw_input(prompt)
     finally:
         subprocess.call(["stty", "echo"])
     return passwd


If you don't want to use an external process, use termios:

import termios, sys

def getpassword(prompt="Password: "):
     fd = sys.stdin.fileno()
     old = termios.tcgetattr(fd)
     new = termios.tcgetattr(fd)
     new[3] = new[3] & ~termios.ECHO          # lflags
     try:
         termios.tcsetattr(fd, termios.TCSADRAIN, new)
         passwd = raw_input(prompt)
     finally:
         termios.tcsetattr(fd, termios.TCSADRAIN, old)
     return passwd


These functions work on any Posix system (including Mac OSX),
but not on Windows.

Hope this helps,

-- HansM

[toc] | [prev] | [next] | [standalone]


#11692

FromSteven D'Aprano <steve+comp.lang.python@pearwood.info>
Date2011-08-18 02:36 +1000
Message-ID<4e4bee1e$0$29981$c3e8da3$5496439d@news.astraweb.com>
In reply to#11686
Hans Mulder wrote:

> Strictly speaking, os.system is deprecated and you should use
> the equivalent invocation of subprocess.call:

Strictly speaking, os.system is *not* deprecated in either Python 2.x or
3.x.

Latest stable documentation for Python 2.7 and 3.2:
http://docs.python.org/library/os.html#os.system
http://docs.python.org/py3k/library/os.html#os.system

And docs in development for 3.3 (unstable):
http://docs.python.org/dev/library/os.html#os.system

Deprecation means that there are active plans to remove the feature. There
are no such plans to remove os.system. What the docs say is much milder:

"The subprocess module provides more powerful facilities for spawning new
processes and retrieving their results; using that module is preferable to
using this function."

Using subprocess may be recommended, but that is not the same as saying that
os.system is deprecated. os.system will not be going away any time in the
foreseeable future.


-- 
Steven

[toc] | [prev] | [next] | [standalone]


#11741

Frompeter <peter.mosley@talk21.com>
Date2011-08-18 01:24 -0700
Message-ID<4b383bcd-c58c-4e67-895a-d70fdf82f9c0@n35g2000yqf.googlegroups.com>
In reply to#11686
On Aug 17, 3:16 pm, Hans Mulder <han...@xs4all.nl> wrote:
> On 17/08/11 10:03:00, peter wrote:
>
> > Is there an equivalent to msvcrt for Linux users?  I haven't found
> > one, and have resorted to some very clumsy code which turns off
> > keyboard excho then reads stdin. Seems such an obvious thing to want
> > to do I am surprised there is not a standard library module for it. Or
> > have I missed someting (wouldn't be the first time!)
>
> The quick and dirty way is to invoke stty(1) using os.system:
>
> import os
>
> def getpassword(prompt="Password: "):
>      try:
>          os.system("stty -echo")
>          passwd = raw_input(prompt)
>      finally:
>          os.system("stty echo")
>      return passwd
>
> Strictly speaking, os.system is deprecated and you should use
> the equivalent invocation of subprocess.call:
>
> import subprocess
>
> def getpassword(prompt="Password: "):
>      try:
>          subprocess.call(["stty", "-echo"])
>          passwd = raw_input(prompt)
>      finally:
>          subprocess.call(["stty", "echo"])
>      return passwd
>
> If you don't want to use an external process, use termios:
>
> import termios, sys
>
> def getpassword(prompt="Password: "):
>      fd = sys.stdin.fileno()
>      old = termios.tcgetattr(fd)
>      new = termios.tcgetattr(fd)
>      new[3] = new[3] & ~termios.ECHO          # lflags
>      try:
>          termios.tcsetattr(fd, termios.TCSADRAIN, new)
>          passwd = raw_input(prompt)
>      finally:
>          termios.tcsetattr(fd, termios.TCSADRAIN, old)
>      return passwd
>
> These functions work on any Posix system (including Mac OSX),
> but not on Windows.
>
> Hope this helps,
>
> -- HansM

This is very similar to my solution, which was to use stty turn off
keyboard echo, then repeatedly read sys.stdin.read(1) until a unique
keystroke had been defined. For example, the 'Insert' key seems to
return a sequence of four codes, namely 27, 91, 50, 126.  It works but
has two disadvantages which I have managed to live with:-

1. As character 27 is used to signal the start of a 'special' key
sequence, it cannot detect a single press of the Esc key. The
workaround is to detect a double press instead.

2. Some keys seem to return different sets of codes depending on the
circumstances.  For example, F1 returns 27,91,91,65 from the command
line, and 27,79,80 from a GUI window. I suspect there may be
variations between flavours of Linux too. The solution is to detect
all possibilities - so far I haven't found any overlaps.

Not pretty, but as I said it works. I know now not to spend time
looking further. Whilst there may be a historical reason for the
current situation, it would be a great convenience for amateur coders
like mayself if the gurus could devise a platform independent version
of mscvrt.

If anyone is interested in the code I can post it, but it's quite long
as it comprises multiple if statements to cover each combination.

Peter

[toc] | [prev] | [next] | [standalone]


#11782

FromDennis Lee Bieber <wlfraed@ix.netcom.com>
Date2011-08-18 09:50 -0700
Message-ID<mailman.178.1313686243.27778.python-list@python.org>
In reply to#11741
On Thu, 18 Aug 2011 01:24:30 -0700 (PDT), peter
<peter.mosley@talk21.com> declaimed the following in
gmane.comp.python.general:

> Not pretty, but as I said it works. I know now not to spend time
> looking further. Whilst there may be a historical reason for the
> current situation, it would be a great convenience for amateur coders
> like mayself if the gurus could devise a platform independent version
> of mscvrt.
>
	What would they call it... It sure wouldn't be "MicroSoft Visual C
RunTime".

	Note that the documentation for msvcrt states that /it/ is how the
getpass module is implemented on Windows.

	Take a look at the bottom of getpass.py and look at the loops it has
to do to handle three different environments.
-- 
	Wulfraed                 Dennis Lee Bieber         AF6VN
        wlfraed@ix.netcom.com    HTTP://wlfraed.home.netcom.com/

[toc] | [prev] | [next] | [standalone]


#11791

FromNobody <nobody@nowhere.com>
Date2011-08-18 18:58 +0100
Message-ID<pan.2011.08.18.17.58.40.391000@nowhere.com>
In reply to#11741
On Thu, 18 Aug 2011 01:24:30 -0700, peter wrote:

> This is very similar to my solution, which was to use stty turn off
> keyboard echo, then repeatedly read sys.stdin.read(1) until a unique
> keystroke had been defined. For example, the 'Insert' key seems to
> return a sequence of four codes, namely 27, 91, 50, 126.  It works but
> has two disadvantages which I have managed to live with:-
> 
> 1. As character 27 is used to signal the start of a 'special' key
> sequence, it cannot detect a single press of the Esc key. The
> workaround is to detect a double press instead.
> 
> 2. Some keys seem to return different sets of codes depending on the
> circumstances.  For example, F1 returns 27,91,91,65 from the command
> line, and 27,79,80 from a GUI window. I suspect there may be
> variations between flavours of Linux too. The solution is to detect
> all possibilities - so far I haven't found any overlaps.

Escape sequences vary between terminals. A given key may have different
escape sequences on the Linux console, xterm, a vt220, etc. The
termcap and terminfo databases exist for this purpose (terminfo is newer).

Some escape sequences vary by "mode". E.g. the cursor keys typically
produce different sequences depending upon whether the terminal is in
"keypad" mode.

The normal solution for distinguishing the escape key from an escape
sequence is a timeout. Unfortunately, it needs to be quite long in order
to reliably support network (ssh, telnet, etc) connections.

> Not pretty, but as I said it works. I know now not to spend time
> looking further. Whilst there may be a historical reason for the
> current situation, it would be a great convenience for amateur coders
> like mayself if the gurus could devise a platform independent version
> of mscvrt.

The platform-independent high-level terminal interface is called "curses".

[toc] | [prev] | [next] | [standalone]


#11693

FromSeebs <usenet-nospam@seebs.net>
Date2011-08-17 16:33 +0000
Message-ID<slrnj4nrpf.clc.usenet-nospam@guild.seebs.net>
In reply to#11664
On 2011-08-17, peter <peter.mosley@talk21.com> wrote:
> Is there an equivalent to msvcrt for Linux users?  I haven't found
> one, and have resorted to some very clumsy code which turns off
> keyboard excho then reads stdin. Seems such an obvious thing to want
> to do I am surprised there is not a standard library module for it. Or
> have I missed someting (wouldn't be the first time!)

There's no direct equivalent to the whole of msvcrt.  The Unixy way to
do stuff like that on the command line is usually curses.  But to make
a long story short:  Unix evolved in a setting where there was often
not a user at *THE* console, and users were often on devices such that
it made sense to have all the line editing happen on the remote end, with
the remote end sending a completed line once the user was done with all
that stuff like backspaces.

Unix programs that do stuff like this for tty input do exist, of course,
but for the most part, they use an entire API designed for creating such
utilities, rather than one or two specialized functions.  (Another part
of the reason for this:  The Unix solution scales nicely to the case where
the five people using your program will be doing so on physically
different hardware terminals which don't use the same escape sequences
for cursor movement.)

Usually when people omit something obvious from a design, it's because of
other constraints or history to the design which make it less obvious.

-s
-- 
Copyright 2011, all wrongs reversed.  Peter Seebach / usenet-nospam@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.

[toc] | [prev] | [next] | [standalone]


#11698

FromTerry Reedy <tjreedy@udel.edu>
Date2011-08-17 13:02 -0400
Message-ID<mailman.136.1313600587.27778.python-list@python.org>
In reply to#11693
On 8/17/2011 12:33 PM, Seebs wrote:
> On 2011-08-17, peter<peter.mosley@talk21.com>  wrote:
>> Is there an equivalent to msvcrt for Linux users?  I haven't found
>> one, and have resorted to some very clumsy code which turns off
>> keyboard excho then reads stdin. Seems such an obvious thing to want
>> to do I am surprised there is not a standard library module for it. Or
>> have I missed someting (wouldn't be the first time!)
>
> There's no direct equivalent to the whole of msvcrt.  The Unixy way to
> do stuff like that on the command line is usually curses.  But to make
> a long story short:  Unix evolved in a setting where there was often
> not a user at *THE* console, and users were often on devices such that
> it made sense to have all the line editing happen on the remote end, with
> the remote end sending a completed line once the user was done with all
> that stuff like backspaces.
>
> Unix programs that do stuff like this for tty input do exist, of course,
> but for the most part, they use an entire API designed for creating such
> utilities, rather than one or two specialized functions.  (Another part
> of the reason for this:  The Unix solution scales nicely to the case where
> the five people using your program will be doing so on physically
> different hardware terminals which don't use the same escape sequences
> for cursor movement.)

The difference is between "Hit <enter> to continue" (which we can do in 
portable Python) versus "Hit any key to continue" (which we cannot, and 
which also leads to the joke about people searching for the 'any' key 
;-). The equivalent contrast for GUIs is "Click OK to continue" versus 
"Click anywhere to continue" If having to click a specific area is okay 
for GUIs, having to hit a specific key for TUIs should be also.


-- 
Terry Jan Reedy

[toc] | [prev] | [next] | [standalone]


#11699

FromSeebs <usenet-nospam@seebs.net>
Date2011-08-17 17:05 +0000
Message-ID<slrnj4nt6n.e0l.usenet-nospam@guild.seebs.net>
In reply to#11698
On 2011-08-17, Terry Reedy <tjreedy@udel.edu> wrote:
> The difference is between "Hit <enter> to continue" (which we can do in 
> portable Python) versus "Hit any key to continue" (which we cannot, and 
> which also leads to the joke about people searching for the 'any' key 
> ;-).

And more importantly, frustration and confusion when people pick control
or shift.

> The equivalent contrast for GUIs is "Click OK to continue" versus 
> "Click anywhere to continue" If having to click a specific area is okay 
> for GUIs, having to hit a specific key for TUIs should be also.

In general I agree.

-s
-- 
Copyright 2011, all wrongs reversed.  Peter Seebach / usenet-nospam@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.

[toc] | [prev] | [next] | [standalone]


#11710

FromSteven D'Aprano <steve+comp.lang.python@pearwood.info>
Date2011-08-18 04:29 +1000
Message-ID<4e4c088c$0$29978$c3e8da3$5496439d@news.astraweb.com>
In reply to#11698
Terry Reedy wrote:

> The difference is between "Hit <enter> to continue" (which we can do in
> portable Python) versus "Hit any key to continue" (which we cannot, and
> which also leads to the joke about people searching for the 'any' key
> ;-). The equivalent contrast for GUIs is "Click OK to continue" versus
> "Click anywhere to continue" If having to click a specific area is okay
> for GUIs, having to hit a specific key for TUIs should be also.

Poor analogy. A better analogy to a GUI would be comparing:


    What would you like to do? Select an option and then click OK:
        ( ) Cancel
        ( ) Print
        (x) Save
                       [__OK__]


versus:


    What would you like to do?
        [__Cancel__]  [__Print__]  [__Save__]


Actually, a better analogy would be a GUI that made you do this:


    What would you like to do? Type the first letter of the option 
    you prefer in the text field, then click the OK button:
        Options:  Cancel | Print | Save
        My option: [ ............ ]    [__OK__]


(ASCII art best viewed with a fixed-width font.)

Generally speaking, the second UI would be preferred.

The raw_input/input UI is well-designed for entering plain text data. It is
extremely poor as a command interface.

Bringing it back to text interfaces, it would be useful to have a text
interface such that commands can be executed using a single key press. You
might want to detect and respond to (say) the arrow keys, or ESC, or P
rather than P<enter>. Curses apps can do it, proof that even under Unix it
is desirable. (Imagine how awkward it would be to use a TUI mail client or
text editor where the only user input was from something like raw_input.)
Unfortunately curses is quite heavyweight for a simple CLI script.

I note also that even the Python interactive interpreter under Linux has an
extremely limited detect-single-keypress capability: Ctrl-C generates a
KeyboardInterrupt without needing to hit Enter, and Ctrl-D exits the
interpreter.



-- 
Steven

[toc] | [prev] | [next] | [standalone]


#11720

FromChris Angelico <rosuav@gmail.com>
Date2011-08-17 23:10 +0100
Message-ID<mailman.149.1313619041.27778.python-list@python.org>
In reply to#11710
On Wed, Aug 17, 2011 at 7:29 PM, Steven D'Aprano
<steve+comp.lang.python@pearwood.info> wrote:
> The raw_input/input UI is well-designed for entering plain text data. It is
> extremely poor as a command interface.
>
> ... (Imagine how awkward it would be to use a TUI mail client or
> text editor where the only user input was from something like raw_input.)

I run a MUD and play several. MUDs by definition have only line-based
input (if you use a raw TELNET client, you have character-based input,
but most MUD clients send entire lines of text at once); yet it is
possible to implement a reasonably-viable file editor. It's not
difficult to become quite proficient with line-based editors,
especially if you rig some client-side support (which I have done on
two of the MUDs).

Line-based input is excellent as a command interface, if commands
consist of verbs and parameters. It's terrible for playing Tetris on.

ChrisA

[toc] | [prev] | [standalone]


Page 2 of 2 — ← Prev page 1 [2]

Back to top | Article view | comp.lang.python


csiph-web