2to3, Python 2 to Python 3 made easy!
Posted On 2020-12-19
Do I need to upgrade from Python 2 to Python 3?
I started to develop my ADS-B tracker software in Python 2 and I delayed the upgrade to Python 3 for a long time. I was thinking it would be pretty difficult! Now that PIP is soon to drop support of Python 2.7, I finally got to it. It was much easier than I expected thanks to 2to3!
The magic of 2to3
You don’t really need to know much about Python 3 to do the upgrade! Just copy all your files in a new Python 3 directory, make sure you have installed all the Python 3 packages you need and use 2to3 and it is done!
cp project_master project_master_py3
sudo apt-get install python3 python3-pip <<your Python 3 packages>>
python3 -m pip install <<your packages>>
2to3 -w *.py
It should almost work…
A little bit of tuning is needed
You may still have some errors due to 2 things:
– Python 3 does not like when mixing space and tab for indentation. It is quite easy to solve by being consistant. Use only spaces or only tabs, whatever is best for you (I don’t have a religion there!).
– Python 3 has a different way to manage strings and bytes. That one is trickier. I solved it by adding 2 functions to change the variable to bytes or to string when needed:
if hasattr(arg, 'encode'): return arg.encode('utf-8')
if hasattr(arg, 'decode'): return arg
if hasattr(arg, 'encode'): return arg
if hasattr(arg, 'decode'): return arg.decode('utf-8')
I just ran my program until it detected all the instances where bytes and strings were mixed.
That’s it, it did the job. My trackers are now running Python 3, and still connect to my online database, tweet when detect new or interesting planes, connect through SigFox when off grid,… as they were doing in Python 2. I didn’t notice an impact on the error rate so far.