检测 IronPython 的最佳方法
我需要编写一个可以在 CPython 和 IronPython 中使用的模块。检测 IronPython 的最佳方法是什么,因为在这种情况下我需要稍微不同的行为?
我注意到 sys.platform 在 CPython 上是“win32”,但在 IronPython 上是“cli”。
是否有另一种首选/标准的检测方法?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Python 2.6 中的新功能是
platform.python_implementation
:这可能是最干净的方法,而且也是最标准的方法。但是,我相信 Jython 仍在运行 2.5,因此我不确定您是否可以依靠它来检测 Jython(但这不是您问题的一部分)。
New in Python 2.6 is
platform.python_implementation
: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).
以下代码适用于 CPython 2.6 和 Iron Python 2.6 (.NET 2.0)。
但不适用于 Iron Python 2.6 (.NET 4.0),platform.py 解析版本号时存在一些问题。我向 Python.org 提交了一个缺陷。修复 platform.py 并不那么困难。
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.
理想情况下:
但不幸的是,平台模块在 Python 实现中的实现不一致(或者在某些情况下根本没有......*咳嗽* Jython *咳嗽*)。
我用这个:
Ideally:
But unfortunately the platform module isn't implemented consistently across Python implementations (or at all in some cases... *cough* Jython *cough*).
I use this:
“cli”(= 公共语言基础设施 = .NET = IronPython)可能是可靠的。
据我所知,您可以在 IronPython 中访问 .NET 库,因此您可以尝试导入 .NET 库,并捕获当 .NET 不可用时抛出的异常(如在 CPython 中)。
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).