module "random" not found when building .exe from IronPython 2.6 script
I am using SharpDevelop to build an executable from my IronPython script. The only hitch is that my script has the line import random which works fine开发者_运维问答 when I run the script through ipy.exe, but when I attempt to build and run an exe from the script in SharpDevelop, I always get the message:
IronPython.Runtime.Exceptions.ImportException: No module named random
Why isn't SharpDevelop 'seeing' random? How can I make it see it?
When you run an IronPython script with ipy.exe the path to the Python Standard Library is typically determined from one of the following:
- The IRONPYTHONPATH environment variable.
- Code in the lib\site.py, next to ipy.exe, that adds the location of the Python Standard Library to the path.
An IronPython executable produced by SharpDevelop will not do these initial setup tasks. So you will need to add some extra startup code before you import the random library. Here are a few ways you can do this:
Add the location of the Python Standard Library to sys.path directly.
import sys sys.path.append(r'c:\python26\lib')
Get the location of the Python Standard Library from the IRONPYTHONPATH environment variable.
from System import Environment pythonPath = Environment.GetEnvironmentVariable("IRONPYTHONPATH") import sys sys.path.append(pythonPath)
Read the location of the Python Standard Library from the registry (HKLM\Software\Python\PythonCore\2.6\PythonPath).
Read the location of the Python Standard Library from a separate config file that you ship with your application.
Another alternative is to compile the parts of the Python Standard Library your application needs into one or more .NET assemblies. That way you will not need the end user of your application to have the Python Standard Library installed.
精彩评论