Running Python with Microsoft.Scripting & IronPython

I can create Python scripts and dynamically run them through Visual Studio / .NET 4.0 as follows:

# testScript.py file: import sys sys.path.append(r'C:\Program Files (x86)\IronPython 2.7.1\Lib') import os os.environ['HTTP_PROXY'] = "127.0.0.1:8888" import urllib2 response = urllib2.urlopen("http://www.google.com") 

and then in the .NET 4.0 WinForms project:

 ScriptEngine engine = Python.CreateEngine(); ScriptSource script = engine.CreateScriptSourceFromFile("testScript.py"); ScriptScope scope = engine.CreateScope(); script.Execute(scope); 

However, the IronPython DLLs that I import do not contain all the standard modules, so I need to do

 import sys sys.path.append(r'C:\Program Files (x86)\IronPython 2.7.1\Lib') 

so that I can run the next 4 lines.

Is there any way to avoid this?

I am going to publish the application, and I do not want to rely on the fact that the file path is the same on all machines!

+4
source share
2 answers

There is an extension method that allows you to do this directly:

 ScriptEngine engine = Python.CreateEngine(); ScriptSource script = engine.CreateScriptSourceFromFile("testScript.py"); ScriptScope scope = engine.CreateScope(); engine.SetSearchPaths(new string[] { "C:\\Program Files (x86)\\IronPython 2.7.1\\Lib" }); script.Execute(scope); 

It is probably best to include stdlib with your application in a private directory rather than relying on installing it, but that is up to you.

+5
source

If you include a copy of the Lib directory in any directory that contains your own scripts, you can use the IRONPYTHONPATH environment IRONPYTHONPATH to work on a hard-coded path.

Install IRONPYTHONPATH before running scripts,

 Environment.SetEnvironmentVariable("IRONPYTHONPATH", @"your_scripts\Lib"); ScriptEngine engine = Python.CreateEngine(); 

and then you can remove the path manipulation from python scripts.

+4
source

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


All Articles