Python versions

From wikinotes
Revision as of 21:09, 31 July 2021 by Will (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

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+

six

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

toplevel helpers

six.reraise(*sys.exc_info())

six.moves

from six.moves.urllib import request
request.Request(..)

future

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+

collections.abc

from collections import MutableMapping      # old
from collections.abc import MutableMapping  # new