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