I am able to create Python scripts and dynamically run them via Visual Studio / .NET 4.0 like this:
# 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")
then in a .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 don't contain all the standard modules and so I have to do the
import sys
sys.path.append(r'C:\Program Files (x86)\IronPython 2.7.1\Lib')
step so that I can run the next 4 lines.
Is there some way I can avoid this?
I'm going to be publishing the application and I don't want to have to rely on the file path being the same on everyone's machine!
There's 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's probably best to include the stdlib with your app in a private directory rather than rely on it being installed, but that's up to you.
If you include a copy of the Lib directory in whichever directory contains your own scripts then you could use the IRONPYTHONPATH
environment variable to work around the hard-coded path.
Set the IRONPYTHONPATH
before running the scripts,
Environment.SetEnvironmentVariable("IRONPYTHONPATH", @"your_scripts\Lib");
ScriptEngine engine = Python.CreateEngine();
and then you should be able to remove the path manipulation from the python scripts.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With