IronPython embedding in C # application - import error on urllib

I have a Python file with the contents:

import re import urllib class A(object): def __init__(self, x): self.x = x def getVal(self): return self.x def __str__(self): return "instance of A with value '%s'" % (self.getVal()) 

I also have a simple C # console project with the following code:

 engine = Python.CreateEngine(); ScriptSource source = engine.CreateScriptSourceFromFile("test.py"); ScriptScope scope = engine.CreateScope(); ObjectOperations op = engine.Operations; source.Execute(scope); // class object created object klaz = scope.GetVariable("A"); // get the class object object instance = op.Call(klaz, "blabla waarde"); // create the instance object method = op.GetMember(instance, "getVal"); // get a method string result = (string)op.Call(method); // call method and get result (9) Console.WriteLine("Result: " + result); //output: 'Result: blabla waarde' 

(I got this from https://stackoverflow.com/a/3126161/ )
If I left the import urllib expression in the Python file, everything will work fine. (which means it finds the re module)
But as soon as I add import urllib or import urllib2 , I get the following exception:

 ImportException was unhandled No module named urllib 

So for some reason he cannot find urllib. I checked the IronPython lib folder and both urllib and urllib 2 definitely exist. The same exception occurs when I import urllib into C # code. ( engine.ImportModule("urllib"); )

Any ideas? I would like to control the import in python code, not in C # code.
(Therefore, I would like to avoid such things: engine.ImportModule("urllib"); )

Edit: Additional information about what I'm actually going to use for this (maybe someone has an alternative):
I will have a main C # application, and python scripts will be used as extensions or plugins for the main application.
I use Python, so I do not need to compile any of the plugins.

+4
source share
3 answers

I have the same problem. Following the suggestion of "Tom E's" in the comments on fuzzyman reply, I could successfully solve the problem. It seems that the problem is not with urllib.py location resolution. We must install it.

You can check the following link to answer the question and answer.

+1
source

I believe that "Lib", located on sys.path from the interactive console, is actually executed inside ipy.exe - and when embedding you will have to add the path manually. Either the engine or the runtime has a SetSourcePaths (or similar) method that allows you to do this.

+4
source

The version of CPython you import must match your version of IronPython. Use CPython v2.5 for IronPython 2.0 or v2.6 for IronPython 2.6.

Try the following:

 import sys sys.path.append(r'\c:\python26\lib') # adjust to whatever version of CPython you have installed. import urllib 
0
source

Source: https://habr.com/ru/post/1300668/


All Articles