我已通过 NuGet 将 IronPython 标准库添加到我的 c#.net4 项目中,后来获得了一些参考资料(IronPython、IronPython.Modules、IronPython.SQLite、IronPython.Wpf、Microsoft.Dynamic、Microsoft.Scripting 等)和“Lib”文件夹包含 python 模块。
现在我尝试在 my file.py 中导入“urllib”模块,但收到 ImportException(没有名为 urllib 的模块)。
我该如何使用 urllib?我应该将 Lib 文件夹复制到项目输出目录还是执行其他操作?
UPD:如果我将所需的模块复制到项目输出目录,则程序无需设置路径即可正常工作。
我可以使用“urllib”作为嵌入式资源或在运行时导入它吗?
Thanks!
Sources:
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')
您可以将 Lib 文件夹复制到输出目录。如果您希望它位于不同的目录中,您可以使用ScriptEngine.SetSearchPaths()
完全控制库路径。
另一种选择是将标准库放入 .zip 文件中并使用添加ScriptEngine.SetSearchPaths()
,这至少减少了要发送的文件数量。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)