Import embedded libs of IronPython

我的梦境 提交于 2019-12-23 15:41:15

问题


I've added IronPython Standart Library via NuGet into my c#.net4 project and later got some references(IronPython, IronPython.Modules, IronPython.SQLite, IronPython.Wpf, Microsoft.Dynamic, Microsoft.Scripting etc) and the 'Lib' folder contains python modules. Now I'm trying to import the 'urllib' module in the my file.py but receiving the ImportException (No module named urllib). How can I use urllib? Should I copy Lib folder to project output directory or do something else?

UPD: If I copy required modules to the project output directory then program works correctly without settings path. May I use 'urllib' as embedded resource or import it in runtime?

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')

回答1:


You can copy the Lib folder to your output directory. If you want it in a different directory you can use ScriptEngine.SetSearchPaths() to have complete control over the library path.

Another option is to put the standard library in a .zip file and add that using ScriptEngine.SetSearchPaths(), which at least reduces the number of files to send around.



来源:https://stackoverflow.com/questions/13878408/import-embedded-libs-of-ironpython

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!