Discussion:
[Tutor] key detection
Jim Mooney Py3.4.3winXP
2015-05-05 21:30:41 UTC
Permalink
Can python detect a keypress? I've looked all over and can't find it. I
don't mean input('blah') and have to press Enter - just detect it directly
like Javascript does. All I find are references using msvcrt, which is
Msoft specific, or using tkinter - but I don't want a whacking big GUI,
just keypress detection. Can I make a simple keyboard event loop without
tkinter?
--
Jim
_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Alan Gauld
2015-05-05 22:36:18 UTC
Permalink
Post by Jim Mooney Py3.4.3winXP
Can python detect a keypress?
That sounds simple but is actually quite tricky
since it's terminal dependent.
Post by Jim Mooney Py3.4.3winXP
like Javascript does. All I find are references using msvcrt, which is
Msoft specific, or using tkinter - but I don't want a whacking big GUI,
You can also use curses on Unix like systems
which is CLI based. But it acts a bit like a GUI, you do need to
initialize the framework ec.

It's described in the Event Driven Programming topic of my tutorial.

There are other ways like using the low level C functions directly from
the C libraries using ctypes, but that brings its own difficulties in
converting Python data into C compatible types etc.

curses is the preferred option on Unix like systems.

There are some third party modules that try to address this in
a system independent manner, they can be found on PyPI but
I can't recommend any of them as I've not used them. I think
Fred Lundh created one such called, maybe, terminal?
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Jim Mooney Py3.4.3winXP
2015-05-05 23:47:24 UTC
Permalink
Post by Jim Mooney Py3.4.3winXP
Can python detect a keypress?
That sounds simple but is actually quite tricky
since it's terminal dependent.
An ancillary question. I found a readchar that purports to install in py2
and 3 but fails in 3. The errors (something from the encodings module)
won't copy from the console, so I thought I could redirect them like so:

python3 setup.py > errors.txt

But that didn't work. How can I get a printout of setup errors so I can
post them? That's something of general use aside from the keyboard loop.
Otherwise, I decided to just use msvcrt for now, which is quite simple, and
put in a try block for win or linux, when I dual boot linux, which I'm
working on. (solving the usual driver problems for a toshiba laptop)
--
Jim

"What a rotten, failed experiment. I'll start over. Maybe dogs instead of
monkeys this time." --God
_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Jim Mooney Py3.4.3winXP
2015-05-06 00:00:36 UTC
Permalink
Post by Jim Mooney Py3.4.3winXP
But that didn't work. How can I get a printout of setup errors so I can
post them?
I remembered how to copy the DOS console. Here is the error. Error wasn't
in setup.py so that wouldn't have worked anyway.

C:\Python34\Lib\site-packages\readchar-1.1.0>python3 setup.py
Traceback (most recent call last):
File "setup.py", line 39, in <module>
long_description=read_description(),
File "setup.py", line 11, in read_description
return fd.read()
File "c:\python34\lib\encodings\cp1252.py", line 23, in decode
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position
2468: cha
racter maps to <undefined>
--
Jim

"What a rotten, failed experiment. I'll start over. Maybe dogs instead of
monkeys this time." --God
_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Steven D'Aprano
2015-05-06 01:35:18 UTC
Permalink
Post by Jim Mooney Py3.4.3winXP
An ancillary question. I found a readchar that purports to install in py2
and 3 but fails in 3. The errors (something from the encodings module)
python3 setup.py > errors.txt
Is this under Linux or another Unix? If so, > only redirects stdout, not
stderr, so you need:

python3 setup.py 2> errors.txt

to capture the errors.

I have no idea if Windows works the same way.
--
Steve
_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Jim Mooney Py3.4.3winXP
2015-05-06 04:02:36 UTC
Permalink
Post by Steven D'Aprano
Is this under Linux or another Unix? If so, > only redirects stdout, not
python3 setup.py 2> errors.txt
to capture the errors.
I have no idea if Windows works the same way.
Damn, that actually worked in windows instead of using their awful screen
copy. What a surprise:

errors.txt

Traceback (most recent call last):
File "setup.py", line 39, in <module>
long_description=read_description(),
File "setup.py", line 11, in read_description
return fd.read()
File "c:\python34\lib\encodings\cp1252.py", line 23, in decode
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position
2468: character maps to <undefined>
--
Jim

"What a rotten, failed experiment. I'll start over. Maybe dogs instead of
monkeys this time." --God
_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Dave Angel
2015-05-06 13:39:39 UTC
Permalink
Post by Jim Mooney Py3.4.3winXP
actually worked in windows instead of using their awful screen
Many people don't realize that you can turn on a better screen copy
feature for the CMD window (DOS box) in Windows.

I've given up Windows, and no longer remember how, but the feature is
called something like auto-copy and can be turned on for all DOS box
windows.

Once on, you select by dragging with the mouse, and insert by
right-click. Still has to be a rectangle, but better than nothing when
redirection lets you down.
--
DaveA
_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Brandon McCaig
2015-05-22 16:58:35 UTC
Permalink
Dave:

Sorry for the late reply, but it sounds like it could help a few people here...
Many people don't realize that you can turn on a better screen copy feature
for the CMD window (DOS box) in Windows.
I've given up Windows, and no longer remember how, but the feature is called
something like auto-copy and can be turned on for all DOS box windows.
Once on, you select by dragging with the mouse, and insert by right-click.
Still has to be a rectangle, but better than nothing when redirection lets
you down.
The feature you're looking for is called "QuickEdit Mode". There is a
checkbox in the Options tab of the cmd.exe properties dialog. While
you're at it, I recommend configuring the cursor size and optionally
the command buffer size. Then switch tabs and see if you can configure
a better font. Then switch to the layout tab and hard-code a
full-screen size for the window. Everybody knows the stupid cmd.exe
window cannot be dynamically sized, but you can manually configure the
screen buffer and window size to get something much more friendly.
cmd.exe sucks, but if you take a few minutes to configure it then it
sucks considerably less. Add clink to make it suck a bit less still.

HTH.

Regards,
--
Brandon McCaig <***@gmail.com> <***@castopulence.org>
Castopulence Software <https://www.castopulence.org/>
Blog <http://www.bambams.ca/>
perl -E '$_=q{V zrna gur orfg jvgu jung V fnl. }.
q{Vg qbrfa'\''g nyjnlf fbhaq gung jnl.};
tr/A-Ma-mN-Zn-z/N-Zn-zA-Ma-m/;say'
_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Mark Lawrence
2015-05-06 04:53:58 UTC
Permalink
Post by Jim Mooney Py3.4.3winXP
Post by Jim Mooney Py3.4.3winXP
Can python detect a keypress?
That sounds simple but is actually quite tricky
since it's terminal dependent.
An ancillary question. I found a readchar that purports to install in py2
and 3 but fails in 3. The errors (something from the encodings module)
python3 setup.py > errors.txt
But that didn't work. How can I get a printout of setup errors so I can
post them? That's something of general use aside from the keyboard loop.
Otherwise, I decided to just use msvcrt for now, which is quite simple, and
put in a try block for win or linux, when I dual boot linux, which I'm
working on. (solving the usual driver problems for a toshiba laptop)
You may find life far easier on Windows with http://conemu.github.io/
--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Alex Kleider
2015-05-06 05:24:14 UTC
Permalink
Post by Jim Mooney Py3.4.3winXP
Can python detect a keypress?
The following works for my (on my Ubuntu platform) system
although probably won't be of much use on a Redmond OS.

#!/usr/bin/env python3
# file: 'readchar.py'
"""
Provides readchar()
Implementation of a way to get a single character of input
without waiting for the user to hit <Enter>.
(OS is Linux, Ubuntu 14.04)
"""

import tty, sys, termios

class ReadChar():
def __enter__(self):
self.fd = sys.stdin.fileno()
self.old_settings = termios.tcgetattr(self.fd)
tty.setraw(sys.stdin.fileno())
return sys.stdin.read(1)
def __exit__(self, type, value, traceback):
termios.tcsetattr(self.fd, termios.TCSADRAIN, self.old_settings)

def readchar():
with ReadChar() as rc:
return rc

def testrc():
print\
("Testing ReadChar: enter a character and we'll report what it is.")
while True:
char = readchar()
if ord(char) <= 32:
print("You entered character with ordinal {}, aka {}."
.format(ord(char), repr(char)))
else:
print("You entered character '{}'."
.format(char))
if char in "^C^D":
break

if __name__ == "__main__":
testrc()

To give credit where credit is due: I seem to remember cobbling this
together
based on something that was discussed on this mailing list quite some
time ago.
i.e. it's not original work:-)


_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Steven D'Aprano
2015-05-06 01:32:45 UTC
Permalink
Post by Jim Mooney Py3.4.3winXP
Can python detect a keypress? I've looked all over and can't find it. I
don't mean input('blah') and have to press Enter - just detect it directly
like Javascript does. All I find are references using msvcrt, which is
Msoft specific, or using tkinter - but I don't want a whacking big GUI,
just keypress detection. Can I make a simple keyboard event loop without
tkinter?
https://code.activestate.com/recipes/577977-get-single-keypress/
--
Steve
_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Jim Mooney Py3.4.3winXP
2015-05-06 04:30:12 UTC
Permalink
Post by Steven D'Aprano
https://code.activestate.com/recipes/577977-get-single-keypress/
That only has a stub for Linux, but I found one that does both. Although,
alas, no IOS version:

http://code.activestate.com/recipes/134892-getch-like-unbuffered-character-reading-from-stdin/

Anyway, I set up msvcrt for now until I install linux - I'm not interested
in the program I mentioned, per se, just the error message - mainly to
know, generally, what sort of thing it's choking on. Errors are useful to
know.
--
Jim
_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Mark Lawrence
2015-05-06 04:51:54 UTC
Permalink
Post by Jim Mooney Py3.4.3winXP
Post by Steven D'Aprano
https://code.activestate.com/recipes/577977-get-single-keypress/
That only has a stub for Linux, but I found one that does both. Although,
http://code.activestate.com/recipes/134892-getch-like-unbuffered-character-reading-from-stdin/
Anyway, I set up msvcrt for now until I install linux - I'm not interested
in the program I mentioned, per se, just the error message - mainly to
know, generally, what sort of thing it's choking on. Errors are useful to
know.
I went a further step from the recipes linked to above and got here
https://pypi.python.org/pypi/readchar
--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Jim Mooney Py3.4.3winXP
2015-05-06 17:41:26 UTC
Permalink
Post by Mark Lawrence
Post by Steven D'Aprano
https://code.activestate.com/recipes/577977-get-single-keypress/
That only has a stub for Linux, but I found one that does both. Although,
http://code.activestate.com/recipes/134892-getch-like-unbuffered-character-reading-from-stdin/
Anyway, I set up msvcrt for now until I install linux - I'm not interested
in the program I mentioned, per se, just the error message - mainly to
know, generally, what sort of thing it's choking on. Errors are useful to
know.
I went a further step from the recipes linked to above and got here
https://pypi.python.org/pypi/readchar
I think that's the one that failed for me but I found out why. I just wrote
the simple snippet below to try msvcrt out. I can add a Linux try block
when I install Linux and actually find a wifi driver for it ;')

I reproduced the error that puzzled me almost immediately. It was from
hitting a function key. The snippet below worked fine for letters and such,
but died when I hit a function key (although not all of them). I was
decoding since msvcrt sends byte strings, but there was nothing in the
utf-8 map for that key. The 2> redirect is sure handy for dos console
error messages - something I'll have to remember ;')

from msvcrt import *

while True:
if kbhit():
key = getch()
if key == b'\xe0' or key == b'\000':
print('special key follows')
key = getch()
print(str(key, encoding='utf-8')) #got rid of this decode after
a function key error
else:
print('The key is: ', str(key, encoding='utf-8'))

Traceback (most recent call last):
File "keyget.py", line 9, in <module>
print(str(key, encoding='utf-8'))
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x85 in position 0:
invalid start byte
--
Jim

"What a rotten, failed experiment. I'll start over. Maybe dogs instead of
monkeys this time." --God
_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Jim Mooney Py3.4.3winXP
2015-05-06 17:56:24 UTC
Permalink
Post by Mark Lawrence
I went a further step from the recipes linked to above and got here
Post by Mark Lawrence
https://pypi.python.org/pypi/readchar
I think that's the one that failed for me
Addendum. That only failed in python 3.4. It worked fine in python 2.7 -
but I rarely use that.
--
Jim
_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Dave Angel
2015-05-06 21:08:39 UTC
Permalink
Post by Jim Mooney Py3.4.3winXP
from msvcrt import *
key = getch()
print('special key follows')
key = getch()
print(str(key, encoding='utf-8')) #got rid of this decode after
a function key error
print('The key is: ', str(key, encoding='utf-8'))
File "keyget.py", line 9, in <module>
print(str(key, encoding='utf-8'))
invalid start byte
I don't know why you would be expecting to get a utf-8 character for the
second byte of a function key code. It's an entirely arbitrary byte
sequence, and not equivalent to anything in Unicode, encoded or not.
--
DaveA
_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Jim Mooney Py3.4.3winXP
2015-05-06 22:24:20 UTC
Permalink
Post by Dave Angel
I don't know why you would be expecting to get a utf-8 character for the
second byte of a function key code. It's an entirely arbitrary byte
sequence, and not equivalent to anything in Unicode, encoded or not
I just didn't think of accounting for function keys until I hit one -
experimental learning. The program I'm working on doesn't require F keys,
but I tried one just to see what would happen ;') It's worth making the
error to reinforce unicode in my head. One item - once I dropped decoding
for special keys, some were printed as hex codes but some as letters. i.e.
F11 was b'\x85', but F9 and F10 were b'C' and b'D', so I assume the second
byte of some function keys just happens to map to utf-8 letters. Sure
enough, when I put in decoding again, F9 and F10 second bytes printed as C
and D, but the program bailed on F11.
--
Jim

"What a rotten, failed experiment. I'll start over. Maybe dogs instead of
monkeys this time." --God
_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Steven D'Aprano
2015-05-06 23:52:25 UTC
Permalink
Post by Jim Mooney Py3.4.3winXP
Post by Dave Angel
I don't know why you would be expecting to get a utf-8 character for the
second byte of a function key code. It's an entirely arbitrary byte
sequence, and not equivalent to anything in Unicode, encoded or not
I just didn't think of accounting for function keys until I hit one -
experimental learning. The program I'm working on doesn't require F keys,
but I tried one just to see what would happen ;') It's worth making the
error to reinforce unicode in my head.
I'm not entirely sure how dealing with something that has nothing to do
with Unicode will reinforce Unicode in your head. That sounds a bit like
saying "I love to cook, I find chopping vegetables really helps my
Python programming..." :-)
Post by Jim Mooney Py3.4.3winXP
One item - once I dropped decoding
for special keys, some were printed as hex codes but some as letters. i.e.
F11 was b'\x85', but F9 and F10 were b'C' and b'D', so I assume the second
byte of some function keys just happens to map to utf-8 letters.
It would be more correct to say they happen to map to ASCII letters.

[Aside: I still don't know whether I like or dislike the (mis)feature
where bytes are displayed by default as if they were ASCII strings.]

It's not quite fair to say that it is an "accident" that it maps to a
UTF-8 character. After all, UTF-8 was carefully designed to be ASCII
compatible, and maybe there was some specific reason why the second byte
of F9 is 0x43 (ASCII 'C'). But perhaps we can say that it is an accident
of history that it partially matches UTF-8. It certainly isn't intended
to match UTF-8.

Think of it this way: if you open a JPEG file in binary mode, to get a
bunch of bytes, and manage by trial and error to find a sequence
somewhere inside the file that decodes as UTF-8 without error, that
doesn't mean that the inventor of the JPEG image format had UTF-8 in
mind when he designed it.
--
Steve
_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Steven D'Aprano
2015-05-06 23:40:16 UTC
Permalink
Post by Jim Mooney Py3.4.3winXP
Post by Steven D'Aprano
https://code.activestate.com/recipes/577977-get-single-keypress/
That only has a stub for Linux,
Er, look again, more closely.

I happen to know the author very well *wink* and know that he run that
specific code under Linux and it works fine. He's never tested it under
Windows, so if it erases your hard drive don't blame him. Blame the
authors of msvcrt.getch.

The general structure of the code goes:

try:
import tty, termios
except ImportError:
# handle Windows and other platforms without
# the tty and termios modules
else:
# define Unix/Linux version of getch
Post by Jim Mooney Py3.4.3winXP
but I found one that does both. Although,
If iOS supports tty and termios, it will just work.
Post by Jim Mooney Py3.4.3winXP
http://code.activestate.com/recipes/134892-getch-like-unbuffered-character-reading-from-stdin/
Ewww. Talk about unnecessary use of classes.


--
Steve
_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Loading...