Which Python implementation am I using?
Steven D'Aprano
steve at pearwood.info
Fri Aug 7 13:27:04 EDT 2015
I have a need to determine which Python implementation is running. Starting
from Python 2.6, we have platform.python_implemention() which (at least in
principle) will do the right thing.
However, for my sins, I also need to support 2.4 and 2.5.
I have come up with this function to determine the Python implementation,
using platform.python_implementation when available, and if not, by trying
to detect the implementation indirectly.
import sys, platform
def implementation():
"""Return the Python implementation."""
def jython():
t = platform.java_ver()
return (t and t[0]) or ('java' in sys.platform.lower())
def ironpython():
if sys.platform == 'cli':
# Common Language Infrastructure == .Net or Mono.
return True
return 'ironpython' in sys.version.lower()
try:
return platform.python_implementation()
except ValueError:
# Work around a bug in some versions of IronPython.
if ironpython():
return 'ironpython'
raise
except AttributeError:
# Python is too old! Probably 2.4 or 2.5.
for func in (jython, ironpython):
if func():
return func.__name__
# Otherwise, it's too hard to tell. Return a default.
return 'python'
Is this the best way to detect Jython and IronPython when
python_implementation isn't available?
How about PyPy, Stackless, or others?
Is there a definitive test (other than python_implementation) for CPython
itself? I'd like to detect that specifically, and leave the default
python-with-no-c for those cases where I really am running some unknown
Python implementation.
Tests should be relatively lightweight, if possible.
Thanks in advance,
--
Steven
More information about the Python-list
mailing list