1

Is there a way to find out the path of a current project in a subfolder?

If I have for instance something like:

/
    main.py
    /utils
        utilities.py
    /foo
        foo.py
        /foo/bar
           bar.py

While coding in /foo/foo.py or in /foo/bar/bar.py I want to include the "utilities" module located at /utils/utilities.py How can I do this by calling some sort of relative path to the project and then just import this helper module?

I am able to retrieve the path of a file being executed with:

os.path.realpath(os.path.abspath(os.path.split(inspect.getfile( inspect.currentframe() ))[0]))

But what I need is the relative or absolute path of the current project.

Thanks in advance.

Marat
  • 15,215
  • 2
  • 39
  • 48
Ivan Juarez
  • 1,413
  • 4
  • 21
  • 30
  • 4
    Are you familiar with [Intra-package references](http://docs.python.org/tutorial/modules.html#intra-package-references)? – Greg Hewgill Sep 11 '12 at 20:48
  • possible dupicate; take a look at: http://stackoverflow.com/a/6098238/1107807 – Don Question Sep 11 '12 at 21:00
  • I got this working with an example provided here: cmd_subfolder = os.path.realpath(os.path.abspath(os.path.join(os.path.split(inspect.getfile( inspect.currentframe() ))[0],"../../utils/"))) – Ivan Juarez Sep 11 '12 at 21:11

2 Answers2

3

You don't need to worry about the path if you set your project up as a package, which in this case should be as simple as putting an empty __init__.py into each folder:

/src
    __init__.py
    main.py
    foo/
        __init__.py
        foo.py
        /bar
        __init__.py
        bar.py
    util/
        __init__.py
        utilities.py

Now, main.py, foo.py and bar.py can import your utilities module via a simple:

from util import utilities
Matthew Trevor
  • 14,354
  • 6
  • 37
  • 50
2

I got this working with an example provided here:

cmd_subfolder = os.path.realpath(os.path.abspath(os.path.join(os.path.split(inspect.getfile( inspect.currentframe() ))[0],"../../utils/")))
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Ivan Juarez
  • 1,413
  • 4
  • 21
  • 30