One day I found a page on the web that covers interpreting input from game pads on Linux. The code is this:
import sys
pipe = open('/dev/input/js0','r')
while 1:
for character in pipe.read(1):
sys.stdout.write(repr(character))
sys.stdout.flush()
The program is used to open the character device file for a Logitech Dual Action game pad connected to a USB port. When I run the program under Python 2.7, I get the expected output:
'\x0c''\xe0''E''\x00''\x01''\x00''\x01''\x01''D''\xe0''E''\x00''\x00''\x00'
'\x01''\x01''\xbc''^''F''\x00''\x01''\x00''\x01''\x05''<''_''F''\x00''\x00'
'\x00''\x01''\x05'
And the like, with button presses generating bytes that are fed to standard output. However, when I run the exact same script with 3.2, I get this:
Traceback (most recent call last):
File "js.py", line 6, in <module>
for character in pipe.read(1):
File "/usr/lib/python3.2/codecs.py", line 300, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf8' codec can't decode byte 0x8d in position 1: invalid start byte
The exact byte location varies, as well as the position of the byte and whether it is a starting or ending byte, but otherwise that’s pretty much all I get. I would like to know what is causing the error and how to fix it. Now, I understand that Python 2 is a great language and that Python 3 builds off of it, but I started learning and am continuing to learn Python 3, and I just would like to stick with that for now.
I am running Ubuntu GNU/Linux 11.10 with Python 2.7 and 3.2.
If you want raw bytes then you need to open it in binary mode.