archive2020

Porting my last Python 2 scripts to Python 3

Python 2 reached end of life on 1 January 2020. How I find and port the small Python 2 scripts that still run on Raspberry Pi and Linux servers.

2 min read#dev#python#raspberry-pi

Python 2 reached end of life on 1 January 2020. The core team no longer fixes bugs or security issues in it. My bigger projects moved long ago. What is left is small stuff: a cron job on a Pi, a sensor logger, a backup helper. They still start with #!/usr/bin/env python, and on Raspbian Buster that command is still Python 2.7. I spent part of the holidays cleaning them up.

Find them

# shebangs that point at python 2 or plain "python"
grep -rlE '^#!.*python(2)?$' ~/bin /opt /usr/local/bin 2>/dev/null

# cron entries and systemd units that call plain python
crontab -l | grep -n 'python '
grep -rn 'ExecStart=.*python ' /etc/systemd/system/

Plain python is the problem. I change every entry to python3 explicitly.

Convert, then read the diff

python3 -m lib2to3 -w -n myscript.py   # -w writes, -n skips the .bak file
git diff myscript.py

2to3 handles print, except Exception, e, dict.iteritems() and most imports. I still read every change.

What 2to3 does not fix

Python 2 behaviour What to do in Python 3
5 / 2 == 2 Use // when you want integer division
str is bytes bytes for serial ports, sockets, I2C; str for text. Decode and encode at the edge
open(f).read() returns bytes Pass encoding='utf-8' for text, or 'rb' for binary
sorted() on mixed types works Raises TypeError. Fix the data

Serial and socket code is where most of my bugs were. ser.readline() now returns b'23.5\n', not '23.5\n', so a comparison with a string is silently false. Compare with bytes, or decode first.

Old libraries like MySQLdb have Python 3 replacements (mysqlclient, PyMySQL). Install them with pip3 or apt install python3-xxx.

Test where it runs

Run the script by hand with python3, then through cron or systemd. Cron has a different PATH and working directory, so a script that works in your shell can still fail there. I port one script, let it run for a day, then do the next one.