开发者

How to import module from current non-default directory

I'm using Python 2.7. I'm rather new to the python langauge. I have two python modules - "Trailcrest.py" and "Glyph.py", both in the same folder, but not in the Python27 folder.

I need to import "Trailcrest.py" into "Glyph.py", but I am getting the message that "no such module exists".

Additionally, whatever means I u开发者_C百科se to import the module needs to not be dependent on a solid-state path. This program is cross-platform, and the path can be changed depending on the user's preferences. However, these two modules will always be in the same folder together.

How do I do this?


If you have Trailcrest.py and Glyph.py in the same folder, importing one into the other is as simple as:

import Trailcrest
import Glyph

If this does not work, there seems to be something wrong with your Python setup. You might want to check what's in sys.path.

import sys
print sys.path


To elaborate a bit on Ferdinand Beyer's answer, sys.path is a list of file locations that the default module importer checks. Some, though not all installations of python will add the current directory or the directory of the __main__ module to the path. To make sure that the paths relative to a given module are importable in that module, do something like this:

import os.path, sys
sys.path.append(os.path.dirname(__file__))

But something like that shouldn't ever make it into a "production" product. Instead, use something like distutils to install the module's package into the python site-packages directory.


This can also be achieved using the environment variable PYTHONPATH which also influences Python's search path. This can be done in a shell script so that the Python files do not need to be altered. If you want it to import from the current working directory use the . notation in bash:

export PYTHONPATH=.
python python_prog.py
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜