Referencing Python “import” assemblies when calling from IronPython in C#

早过忘川 提交于 2019-12-22 01:34:14

问题


I'm a complete noob when it comes to IronPython. I need to call a py script from an ASP.NET website, and have the following code:

var ipy = IronPython.Hosting.Python.CreateRuntime();
dynamic test = ipy.UseFile(Server.MapPath(@"~\python\test.py"));
test.DoWork();

The version of IronPython I'm using is 2.7.

The 3rd party python file I need to call has the following import directives:

import sys
from array import *
from subprocess import *

I'm receiving the error "No module named subprocess". I've copied the subprocess.py file from the IronPython installation Lib directory, but I assume I need to link to it in the C# code?

Thanks.

EDIT:

I found the solution:

ScriptEngine scriptEngine = Python.CreateEngine();

var sp = scriptEngine.GetSearchPaths();
sp.Add(Server.MapPath(@"~\python\lib"));
scriptEngine.SetSearchPaths(sp);

var scope = scriptEngine.Runtime.ExecuteFile(Server.MapPath(@"~\python\test.py"));

If anyone has any comments/improvements please feel free to elaborate seeing as I'm in new ground with all this Python/IronPython malarky.


回答1:


An alternate way of doing this:

dynamic sys = scriptEngine.ImportModule("sys");            
sys.path.append(somePath);


来源:https://stackoverflow.com/questions/6557494/referencing-python-import-assemblies-when-calling-from-ironpython-in-c-sharp

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