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?
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);
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