Appending paths relative to the current file to sys.path

G

Greg McIntyre

Out of interest, are there any standard Python modules that do this:

def appendRelativeIncludePath(*relpath):
dir = os.path.abspath(os.path.join(os.path.dirname(__file__), *relpath))
if not dir in sys.path:
sys.path.append(dir)

I ask because I often find myself doing this:

----
# myproject/lib/mymodule/test/test.py

if __name__ == '__main__':
import os.path
import sys

dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..',
'..'))
if not dir in sys.path:
sys.path.append(dir)

import mymodule # it's always 2 directories up from here

----

And it seems like a lot to type so often. I can't factor out this
functionality unless I create a little module for doing this and install
it in a standard include path. You see I dream of doing this:

----
# myproject/lib/mymodule/test/test.py

if __name__ == '__main__':
import astandardmodule
astandardmodule.appendRelativeIncludePath('..', '..')
import mymodule
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,813
Latest member
lawrwtwinkle111

Latest Threads

Top