Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > sys.path and importing modules from other directories

Thread Tools

sys.path and importing modules from other directories

Martin P. Hellwig
Posts: n/a
Hello all,

I had some troubles in the past how to arrange my packages and modules,
because I usually don't develop my stuff in the Lib\site-packages
directory I have some troubles when importing depending modules that are
in 'sibling' directories. Like in the following scenario:
- common\
- - __init__
- - something
- other\
- - __init__
- - working_on

So when I am busy with 'working_on' and want to import from common
something it won't let me do that because I don't have pkg_root in my
path. No biggy here, I just add the pkg_root to the path. Once I am
finished most of the time all modules are initiated from a module
directly at the pkg_root level so then importing works without worries.

However it has irritated me enough that I wrote a little script I called
'' that I put in my python path that does these things
for me, so that I only need to import that one and set the parent path,
probably I missed a point here somewhere but if not maybe somebody else
finds it useful.

So while I am developing the depending modules, these modules begin with:
import relative_path

import os, sys

def getparent(depth=0):
"Returns the absolute pathname of (grand)parents directory."
# By default it returns the current working directory.
# The level of 'grand' is set by depth.

getcwd = os.getcwd
sep = os.sep
abspath = os.path.abspath
if depth == 0:
grand = None
grand = depth * -1

# Main function
# From the current working directory get the absolute path,
# split it and join the wanted portion of the list.
pathname = sep.join(abspath(getcwd()).split(sep)[:grand])

# Make sure to throw an exception if depth results in an empty string.
if len(pathname) == 0:
raise_string = "(grand)Parent depth of %s is before root." % depth

def add_package_root(directory=1):
"Add a parent directory relative to cwd to sys.path, default the

Reply With Quote

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
Importing v reloading modules modules Peter Peyman Puk Python 0 03-19-2010 05:09 PM
How to access web.sitemap file from other virtual directories other than the current application root folder? ASP .Net 0 08-07-2006 08:26 PM
Extracting Directories and Sub Directories and Counting Ron Smith Perl Misc 5 11-02-2004 11:23 PM
Importing modules from within other modules Tobiah Python 2 09-14-2003 09:18 PM