The existing guides for porting python 2 to python 3 generally say "...then you run your unit tests and fix any problems you find." This is awkward if you don't have unit tests. While, you will not escape without testing, (perhaps by your angry users in production), you can save little time by:
- Before the conversion, compile your code to python 2 , to establish it isn't already broken
- After the conversion, see if you can compile your code to python 3
- After the conversion, run pylint --py3k
This snippet will compile your code as python2 , it is meant to be called with from a larger python 3 script with something like subprocess.check_output. This snippet will not catch run time errors like “undefined variable” . It will catch compile time errors like “bad indent”
#!/usr/bin/env python import py_compile, sys print("compiling for python 2 %s"%(sys.argv)) py_compile.compile(sys.argv, doraise=True)
This sub-routine will compile your code as python3
def compile_python3_ok(file): try: py_compile.compile(file, doraise=True) except py_compile.PyCompileError as the_exception: msg = "\nERROR FAIL python3 compile %s\n"%(file) sys.stderr.write(msg) sys.stderr.write("\n"+ str(the_exception))
You can install pylint with
sudo apt install python3-pip pip3 install pylint export PATH=/home/$USER/.local/bin:$PATH
This snippit will run pylint with python 3 checkers
#!/us/bin/python3 import subprocess,sys def run_(cmd): try: log_me = subprocess.check_output(cmd.split(), stderr=subprocess.STDOUT) print(log_me) except subprocess.CalledProcessError as the_exception: msg = "ERROR FAIL %s\n"%(cmd) sys.stderr.write(msg) sys.stderr(the_exception.output) CHECKS_TO_SKIP='check99,check22' file='/path/to/file' run_("pylint --py3k --disable=%s %s"%(CHECKS_TO_SKIP,file))
Pylint is kinda like having unit tests, in that you should understand the problems it calls out and either fix them or skip the checks and kinda not in that unlike 100% test coverage, you will miss some problems.
- The The Conservative Python 3 Porting Guide turned me on to pylint --py3k
- A stack exchange thread on compiling python without executing turned me on to py_compile
For simplicity, the code examples here are stripped of useful but distracting bits like logging and conversions that 2to3 doesn't handle. Eventually, I'll strip out my employer's proprietary things and put the full script on GitHub. Sooner rather than later, if somebody shows an interest in the fuller code.