Question

Is there a way to detect that the interpreter that executes the code is Jython or CPython?

I have another post: Jython does not catch Exceptions. For this case, if I know the interpreter is Jython, I can have different code that should work.

if JYTHON:
    sys.path.insert(0, os.path.dirname(__file__))
    from utils import *
else:
    from .utils import *
Was it helpful?

Solution

There is an official way to do it! :-) Please have a look at

http://docs.python.org/2/library/platform.html#platform.python_implementation

Returns a string identifying the Python implementation. Possible return values are: ‘CPython’, ‘IronPython’, ‘Jython’, ‘PyPy’.

New in version 2.6.

I did not know that before.

Old answer:

There probably is no standardized interface, but you can use some educated guessing, based on e.g. sys.executable (http://docs.python.org/2/library/sys.html#sys.executable), and sys.version. Furthermore, some interpreters for sure provide features that are specific to them, which you can make use of.

OTHER TIPS

I'm not sure this is safe way, but I got a hint from Find full path of the Python interpreter?.

With print sys.executable, I have different results.

context> jython context/context.py
None
context> python context/context.py
/usr/bin/python

So, checking sys.executable might be one way for the checking.

Might not be the best way, but to detect Jython, couldn't you just try to import something from Java?

try:
    import java.lang.System
    print "Jython!"
except:
    print "Not Jython"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top