Skip to main content
 首页 » 编程设计

datetime之不能在 IronPython 中使用 DateTime

2024年01月11日57zhengyun_ustc

我像这样在 C# webapp 中托管我的 IronPython:

var engine = Python.CreateEngine(); 
var scope = engine.CreateScope(); 
var script = Engine.CreateScriptSourceFromString(pythonCode, SourceCodeKind.Statements); 
script.Execute(scope); 

我的 python 代码如下所示:

import clr 
clr.AddReference('System.Core') 
 
from System import DateTime 
theDate = DateTime.Today() 

产生此错误的原因:

IronPython.Runtime.Exceptions.ImportException: Cannot import name DateTime  

我在 Google 上花了一些时间,我发现的大部分代码似乎都不再有效了。

我的 IronPython 运行时版本是 v2.0.50727 - 我应该升级吗?不过,我本以为 DateTime 会早点进来?

请您参考如下方法:

尝试添加对 mscorlib 的引用而不是 System.Core。我们在某些时候更改了默认托管行为(2.0.1?2.0.2?),以便在托管时默认完成。您可以通过您的托管代码执行此操作:

engine.Runtime.LoadAssembly(typeof(string).Assembly);