You just want to pass a parameter to the script? Sure, that's easy.
The main way to do that is by using sys.argv
:
import sys
path = sys.argv[1]
sys.path.append(path)
import urllib
import httplib
Then instead of doing this:
py.exe myscript.py
You do this:
py.exe myscript.py "C:\Program Files (x86)\IronPython 2.7\Lib"
If you're running this directly from within a .NET launcher program, you can also just insert the variable dynamically:
PYthon_Script.SetVariable("path", "C:\Program Files (x86)\IronPython 2.7\Lib")
Then, from within the script, you can use that variable.
Or you can even modify sys.path
itself from the launcher. See the Runtime
docs for details.
If you want to add multiple paths, just change these two lines:
paths = sys.argv[1:]
sys.path.extend(paths)
If you want something that sticks around in your environment, so you don't have to pass it every time, that's what environment variables are for.
There's actually a standard environment variable named IRONPYTHONPATH
that should work without you having to do anything. I've never used it myself, but if it works, you don't need to do anything explicit in your code at all. Just set it in your cmd.exe
shell, in your Control Panel, in the C# program you're launching myscript.py
from, whatever's appropriate. This answer has examples for the first two. (They're setting PYTHONPATH
, which affects CPython, instead of IRONPYTHONPATH
, which affects IronPython, but it should be obvious what to change.)
If that doesn't work, you can do the same thing manually:
import os
import sys
path = os.environ['MY_IRONPYTHON_EXTRA_PATH']
sys.path.append(path)
import urllib
import httplib
Now, you can set that MY_IRONPYTHON_EXTRA_PATH
environment variable instead of IRONPYTHON_PATH
.
Here, because you just have a string instead of a list, if you want to specify multiple paths, you need to add a separator. The standard path separator on Windows is a semicolon. So:
paths = os.environ['MY_IRONPYTHON_EXTRA_PATH'].split(';')
sys.path.extend(paths)