4

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!

2 Answers 2

5

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.

2
  • Thanks! Does including the standard lib meaning copying the entire "Lib" folder and all the associated .py files or is there a single file I can include.
    – Chad
    Commented Feb 7, 2012 at 1:52
  • 1
    No, you'd have to copy the whole folder. 2.7.2 will include zipimport so you should be able to put it in a zip file, but I haven't tried it.
    – Jeff Hardy
    Commented Feb 7, 2012 at 20:37
4

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.