6

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 *
Community
  • 1
  • 1
prosseek
  • 182,215
  • 215
  • 566
  • 871

3 Answers3

8

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.

Dr. Jan-Philip Gehrcke
  • 33,287
  • 14
  • 85
  • 130
  • 1
    Note: starting from python3.3 there's also [`sys.implementation`](http://docs.python.org/3.3/library/sys.html#sys.implementation) which contains the name and version of the implementation and might contain other relevant information. – Bakuriu Mar 10 '14 at 16:33
1

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.

Community
  • 1
  • 1
prosseek
  • 182,215
  • 215
  • 566
  • 871
0

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"
SlightlyCuban
  • 3,185
  • 1
  • 20
  • 31