views:

117

answers:

3

I need to write a module which will be used from both CPython and IronPython. What's the best way to detect IronPython, since I need a slightly different behaviour in that case?

I noticed that sys.platform is "win32" on CPython, but "cli" on IronPython.

Is there another preferred/standard way of detecting it?

A: 

The "cli" (= Common Language Infrastructure = .NET = IronPython) is probably reliable.

As far as I know, you can access .NET libraries within IronPython, so you could try importing a .NET library, and catch the exception it throws when .NET is not available (as in CPython).

LukeN
I always thought CLI was command line interface. Acronyms really are running out: http://www.dilbert.com/fast/1993-06-23/.
extraneon
It does mean both!
LukeN
+4  A: 

New in Python 2.6 is platform.python_implementation:

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

That's probably the cleanest way to do it, and that's about as standard as it gets. However, I believe Jython is still running 2.5, so I'm not sure you can rely on this to detect Jython just yet (but that wasn't part of your question anyway).

Mark Rushakoff
seems to be a little broken in the current IronPython 2.6.1 implementation :)
Adal
+1  A: 

The following code will work with CPython 2.6 and Iron Python 2.6 (.NET 2.0). But will not work with Iron Python 2.6 (.NET 4.0), there is some issue with platform.py parsing the version number. I submitted a defect to Python.org. Fixing platform.py is not that difficult.

import sys
import platform

def IsIronPython():
    return platform.python_implementation().lower().find("ironpython")!=-1

print IsIronPython()
Frederic Torres