CodeMouse92
CodeMouse92

Reputation: 6898

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 use 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?

Upvotes: 0

Views: 8485

Answers (3)

Pierz
Pierz

Reputation: 8118

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

Upvotes: 1

SingleNegationElimination
SingleNegationElimination

Reputation: 156148

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.

Upvotes: 2

Ferdinand Beyer
Ferdinand Beyer

Reputation: 67147

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

Upvotes: 3

Related Questions