0

I have a python project structured like this:

root/
    __init__.py
    coolstuff.py
    moduleA/
        __init__.py
        myscript.py

When my working directory is moduleA, how can I run myscript.py, knowing that it needs to have access to coolstuff ?

EDIT: I am aware of the $PYTHONPATH solution but I would like to know which other solutions exist

Florentin Hennecker
  • 1,974
  • 23
  • 37

3 Answers3

1

Include your root directory to path and import your package. Include the following code in myscript.py.

import sys
from os.path import dirname,abspath
sys.path.append(dirname(dirname(abspath(__file__))))
import coolstuff
# do cool stuff

Hope this helps!

Edit: added import sys

Neil Yoga Crypto
  • 615
  • 5
  • 16
  • Ah, interesting answer! There is still one thing that bothers me about it though; this solution requires you to know where you are in the hierarchy. Would there be a way to do this by defining `root` as the top-level package and avoid doing a hardcoded number of `dirname`s ? – Florentin Hennecker Feb 08 '18 at 10:28
  • I have no knowledge of such solution, but I don't see a problem in knowing the hierarchy of your own project and including 3 rules at the top of your scripts. – Neil Yoga Crypto Feb 08 '18 at 10:35
  • 1
    If by run you mean to execute so that it's its own `__main__` then no, I do not think so. See: https://docs.python.org/3.6/tutorial/modules.html#intra-package-references. Esp. last paragraph. In other words. Directly executed script has no knowledge of a package the directory structure may suggest it is being part of. – Ondrej K. Feb 08 '18 at 10:36
0

You can import sys and import the actual directory where your coolstuff.py exist.

Eg:

import sys
sys.path.insert(0,"/root")
import coolstuff

Note: If you are using Windows use the path like this - "C:\Users\test\Documents" (Considering your coolstuff.py is residing in Documents)

__init__.py is not required for this method.

Hope this help you!

MVR
  • 31
  • 2
0

Add path of your project to PYTHONPATH :

export PYTHONPATH =$PYTHONPATH:/xyz/root/

or from python like:

import sys
sys.path.append("/xyz/root/")# path to your project directory

Now you can access all the module from your root directory by simply impporting.

Advay Umare
  • 432
  • 10
  • 23