0

New to using sys.path to enable module import from another directory, so I'm sure this is a noob question but:

Is it possible to not have to use the full/explicit or absolute file path when using sys.path to access a Python script in another directory, but instead, to only provide the directory path that's local to the module file structure?

Currently, I have the following directory structure:

MyModule/
     NAME/
         __init__.py
     bin/
         userinfo.py
         __init__.py
     docs/
     setup.py
     tests/
         NAME_tests.py
         __init__.py

Within the setup.py file, I have it import the userinfo.py script, which just asks the users for some info during installation. In the setup.py file, the lines that call the userinfo.py script look like this:

import sys
sys.path.insert(0, '/Users/malvin/PythonDev/projects/MyModule/bin')
import userinfo 

This works fine, because I know the entire file path where the userinfo.py file is, but obviously this doesn't work for someone who's trying to install the module because (obviously) there's no way to anticipate the file path on the user's system.

My question: Is there a method wherein I can import the userinfo.py file (which lives in the /bin folder) without having the entire system file path (that goes all the way up to /Users) ? In other words, I'd like to just have something like:

 import sys
 sys.path.insert(0, 'MyModule/bin')
 import userinfo

But I know this doesn't work.

AdjunctProfessorFalcon
  • 1,790
  • 6
  • 26
  • 62

1 Answers1

1

You can use the dot (./) notation for the current working directory to establish a relative path.

For example:

(syspathinsert)macbook:syspathinsert joeyoung$ pwd
/Users/joeyoung/web/stackoverflow/syspathinsert
(syspathinsert)macbook:syspathinsert joeyoung$ tree
.
├── MyModule.py
└── bin
    ├── userinfo.py
    └── userinfo.pyc

1 directory, 3 files
(syspathinsert)macbook:syspathinsert joeyoung$ cat ./bin/userinfo.py
def say_hello():
    print "hello there"

(syspathinsert)macbook:syspathinsert joeyoung$ cat MyModule.py 
import sys
sys.path.insert(0, './bin')
import userinfo

userinfo.say_hello()
(syspathinsert)macbook:syspathinsert joeyoung$ python MyModule.py 
hello there
Joe Young
  • 5,749
  • 3
  • 28
  • 27
  • I've seen a lot of debate about sys.path.insert vs sys.path.append, what's better to use in this case? – AdjunctProfessorFalcon Aug 17 '15 at 03:36
  • 1
    I honestly don't have much experience using either of those because I try to use virtualenv for all of my projects. Personally I would go for something like this: http://stackoverflow.com/questions/10738919/how-do-i-add-a-path-to-pythonpath-in-virtualenv – Joe Young Aug 17 '15 at 05:18