Can't use DateTime in IronPython

别来无恙 提交于 2019-11-29 19:56:43

问题


I'm hosting my IronPython in a C# webapp like so:

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

And my python code looks like this:

import clr
clr.AddReference('System.Core')

from System import DateTime
theDate = DateTime.Today()

Which generates this error:

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

I've spent some time on Google and most of the code I found doesn't seem to work anymore.

My IronPython Runtime Version is v2.0.50727 - should I be upgrading? I'd have thought DateTime would've been in from early doors though?


回答1:


Try adding a reference to mscorlib instead of System.Core. We changed the default hosting behavior at some point (2.0.1? 2.0.2?) so that this is done by default when hosting. You can do this from your hosting code with:

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



回答2:


Just checked, and the problem is that you're trying to call Today as a method instead of a property. Try this instead (no need to add a reference to System.Core):

import clr
from System import DateTime
theDate = DateTime.Today
print theDate


来源:https://stackoverflow.com/questions/1472553/cant-use-datetime-in-ironpython

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!