我已经通过NuGet将IronPython标准库添加到了我的c#.net4项目中,后来获得了一些引用(IronPython、IronPython.Modules、IronPython.SQLite、IronPython.Wpf、Microsoft.Dynamic、Microsoft.Scripting等),而'Lib‘文件夹中包含了python模块。现在,我试图在我的file.py中导入'urllib‘模块,但是接收到ImportException (没有模块名为urllib)。我如何使用urllib?我应该将Lib文件夹复制到项目输出目录,还是执行其他操作?
UPD:如果我将所需的模块复制到项目输出目录,那么程序在没有设置路径的情况下正确工作。我可以使用'urllib‘作为嵌入式资源或者在运行时导入它吗?
谢谢!
资料来源:
public static void Main(string[] args)
{
var url = new Uri("www.microsoft.com");
var r = PythonHelper.Get(url);
}
public static class PythonHelper
{
public static string Get(Uri url)
{
var programPath = @"PySources\GetPage.py";
var py = new Py(programPath);
py.Scope.SetVariable("url", url.ToString());
py.Source.Execute();
var result = py.Scope.GetVariable<string>("result");
return result;
}
private class Py
{
public ScriptScope Scope { get; private set; }
public ScriptSource Source { get; private set; }
public Py(string pyPath)
{
var pyEngine = Python.CreateEngine();
Scope = pyEngine.CreateScope();
Source = pyEngine.CreateScriptSourceFromFile(pyPath);
}
public void Execute()
{
Source.Execute(Scope);
}
}
}
GetPage.py:
#!/usr/bin/env python
# -*- coding: windows-1251 -*-
#coding=windows-1251
#encoding=windows-1251
import clr
clr.AddReference("IronPython")
clr.AddReference('IronPython.Modules')
import urllib
user_agent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11"
headers = { 'User-Agent' : user_agent }
result = urllib.urlopen(url, '' ,headers).read().decode('utf-8')发布于 2012-12-14 17:06:36
可以将Lib文件夹复制到输出目录。如果您希望它位于另一个目录中,可以使用ScriptEngine.SetSearchPaths()对库路径进行完全控制。
另一种选择是将标准库放在.zip文件中,并使用ScriptEngine.SetSearchPaths()添加它,这至少减少了要发送的文件数量。
https://stackoverflow.com/questions/13878408
复制相似问题