Python versions

From wikinotes

Python Interpreter Info

import sys
import platform

sys.executable       # the running python interpreter
sys.version_info()   # running python version
platform.libc_ver()  # libc that python was built with

python 2-3+


Several libraries were moved in python3. The module six helps handle the transition between them.

toplevel helpers



from six.moves.urllib import request


Python includes the __future__ module with backports of features to come. It is helpful, but not a silver bullet. In particular, using unicode_literals can cause issues with libraries that are not built to support them.

from __future__ import absolute_import, division, print_function, unicode_literals

unicode as default

python3 now uses unicode by default for it's strings. terminals emulators, sockets, etc generally use bytestrings so you need to be careful to convert your string encoding as soon as possible.

b'abc'   # bytestring
u'abc'   # unicode string

b'abc'.decode('utf-8')  # bytestring-to-unicode
u'abc'.encode('utf-8')  # unicode-to-bytestring

subprocess output

While python3 now uses unicode, most of the other programs that you will be interacting with (including the SHELL), will not. For all subprocess commands, you should use the argument universal_newlines=True which converts your shell's bytestrings into unicode.

subprocess.check_output( shlex.split('ls -la'), universal_newlines=True )

python 3.7+

from collections import MutableMapping      # old
from import MutableMapping  # new