Before you can use the Python Standard Library to create applications, you must provide a means for IronPython to find the Standard Library so it can import modules. You have three options for performing this task.
- Create an environment variable named IRONPYTHONPATH and provide the path to the Standard Library through it.
- Manually add the path to the import search path (discussed later in this section). The advantage of this method is that the import requirements move with the application. However, if the user has their copy of the Standard Library in a different location (or doesn’t have the Standard Library installed at all), the change can break your application.
- Add the path to site.py, which is located in the Program FilesIronPython 2.6Lib directory of your machine. The interpreter loads this file every time it starts, so you can be sure that everyone using the IronPython interpreter on your machine will have the required access. As with the IRONPYTHONPATH environment variable, this solution works on the current machine only.
Manually Adding the Import Search Path
In order to manually add the import search path, you need to add code to every application created. The code isn’t long or hard to understand, but you must add it to every application that requires the Standard Library or the application won’t be able to access it. Here’s an example of the code you need.
In this case, my copy of the Standard Library is located in C:Python26Lib, which is the default setup. You need to change this value to match your system. After you make the change, you can verify that it’s correct by using the following code.
All that this code does is display the last path added to sys.path. If you see the appropriate path, you know you’re ready to go.
Modifying the Site.py File
It’s less convenient to modify the Site.py file than it is to use the other two techniques, but you’re also sure that every application will see the path addition when you modify Site.py. Of course, if you reinstall IronPython, it will overwrite your Site.py, and you’ll need to remember to make the change again. As previously mentioned, the Site.py file is located in the Program Files IronPython 2.6Lib directory of your machine. Open this file with your editor and add the following code to the top of the file:
Make sure you change C:Python26Lib to match the location of the Standard Library on your machine. This example uses the default location. After you save the file, restart the interpreter and you should see the path added to the sys.path attribute.
An interesting side effect of using the Site.py file is that the Standard Library path will appear before the IronPython paths, which means that the Python Standard Library receives preferential treatment. Remember that you can always tell the interpreter not to load the Site.py file by using the –S command line switch.