我已经通过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')
Run Code Online (Sandbox Code Playgroud)
您可以将Lib文件夹复制到输出目录.如果您希望它位于不同的目录中,您可以使用它ScriptEngine.SetSearchPaths()来完全控制库路径.
另一种选择是将标准库放在.zip文件中并使用ScriptEngine.SetSearchPaths()它来添加,这至少减少了要发送的文件数量.
| 归档时间: |
|
| 查看次数: |
1818 次 |
| 最近记录: |