1

I know this is a worn out topic but the import mechanism/s in python is still confusing the masses. What I want is the ability to import a custom module that is in a parent directory in a way that allows me to take a project to another environment and have all of the imports work. For example a structure like this:

repo 
  |--- folder1
  |       |--- script1.py
  |--- folder2       
  |       |--- script2.py 
  |--- utils
          |--- some-util.py

How can I import from some-util.py in both script1 and script2? The idea is that I could clone the repo into a remote host and run scripts from folders 1 and 2 that may have the shared dependency of some-util.py only I don't want to have to run anything before hand. I want to be able to:

connect to box

git clone repo
python repo/folder1/script1.py

contents of script1 and script2:

import some-util

<code>

EDIT: I forgot to mention that occasionally the scripts need to be run from another directory like: /nas/some_folder/repo/folder1/script1.py args..

Also, the box is limited to python 2.7.5

1 Answers1

0

The trick is to implement as your scripts as modules (read here and here for an overview of what the python -m switch means).

Here is a structure, also notice every directory contains an (empty file) named __init__.py:

repo/
|____utils/
| |____someutil.py
| |___ __init__.py
|___ __init__.py
|____folder1/
  |____script1.py
  |___ __init__.py

utils.someutil may contain something like this:

def say_hello():
    return "Hello World."

And your script1.py may contain something like:

from ..utils.someutil import say_hello

if __name__ == "__main__":
    print(say_hello())

Then running the following:

python -m repo.folder1.script1

... produces:

Hello World.
Alexander L. Hayes
  • 3,892
  • 4
  • 13
  • 34
  • Your answer works exactly as you posted. Thanks showing how to do that, however I forgot to mention (see edit) that I need to be able to run the scripts from anywhere on the linux server as well. Your answer only works if you are a level above the root (repo) dir. Otherwise you get: `No module named .repo.folder1` – Preston Taylor Apr 15 '21 at 15:33