我有一个Python文件,内容如下:
import re
import urllib
class A(object):
def __init__(self, x):
self.x = x
def getVal(self):
return self.x
def __str__(self):
return "instance of A with value '%s'" % (self.getVal())
我也有一个简单的C#控制台项目,其中包含以下代码:
engine = Python.CreateEngine();
ScriptSource source = engine.CreateScriptSourceFromFile("test.py");
ScriptScope scope = engine.CreateScope();
ObjectOperations op = engine.Operations;
source.Execute(scope); // class object created
object klaz = scope.GetVariable("A"); // get the class object
object instance = op.Call(klaz, "blabla waarde"); // create the instance
object method = op.GetMember(instance, "getVal"); // get a method
string result = (string)op.Call(method); // call method and get result (9)
Console.WriteLine("Result: " + result); //output: 'Result: blabla waarde'
(我从这个stackoverflow问题和答案中得到了这个内容)
如果我在Python文件中省略了import urllib
语句,一切都正常。(意味着它能找到re模块)
但是,一旦我添加了import urllib
或import urllib2
,就会出现以下异常:
ImportException was unhandled
No module named urllib
一些方式无法找到urllib。我检查了IronPython lib文件夹,urllib和urllib 2肯定在那里。 当我在C#代码中导入urllib时,会抛出相同的异常。(engine.ImportModule("urllib");)
有什么想法吗? 我想在python代码中管理导入,而不是在C#代码中管理。 (所以我想避免这样的事情:engine.ImportModule("urllib");)
编辑: 关于我实际将要使用它的一些额外信息(也许有人有替代方案): 我将拥有一个主C#应用程序,python脚本将用作主应用程序的扩展或插件。 我使用Python,这样就不需要编译任何插件。
['.', 'C:\\DATA\\My Dropbox\\Projects\\C#\\IronPython reference\\DynamicTest\\DynamicTest\\bin\\Debug\\Lib']
(我的项目位置)。我只需要找到正确的函数来添加正确的库路径。但这将留待明天。这也意味着该程序的用户需要安装 IronPython 吗?我希望当 C# 应用程序被编译并包含了 IronPython DLL 文件时,程序能够运行。(除非我也添加了 IronPython 库?) - Jeroen Pelgrimssource.Execute(scope);
行上遇到了语法异常(无效语法):/ - Jeroen Pelgrims