0

I have a project structure, like so:

 └──     auto/
 │  ├────     __init__.py
 │  └────     __pycache__/
 │  ├────     deploy
 │  ├────     destroy
 │  └────     helpers/
 │  │  ├────     __init__.py
 │  │  ├────     cli.py
 │  │  └────     zip.py
 │  └────     synth
└──     src/
 │  ├────     __init__.py
 │  ├────     main.py
 │  └────     models/
 │  │  ├────     __init__.py
 │  │  ├────     filter.py
 │  │  └────     json_extract_config.py
 │  └────     utils/
 │  │  ├────     __init__.py
 │  │  └────     json_extractor.py

I am trying to call the script synth in the ./auto/synth location.

The synth file is a script with a shebang at the top #!/usr/bin/env python3

It imports a function from the ./auto/helpers/zip.py file.

When I run, ./auto/synth from the root folder it throws an error:

from auto.helpers.zip import zip_folder

ModuleNotFoundError: No module named 'auto'

Although when I run PYTHONPATH="$PWD" ./auto/synth the script executes successfully.

Can someone help me understand this behaviour and how to avoid it so that my scripts can be run normally without having to change the PYTHONOPATH?

Thanks in advance.

Ben Muller
  • 221
  • 1
  • 4
  • 10

1 Answers1

0

If you are using python version 3.3+ you do not need to use the __init__.py files anymore, as the namespacing is built into the modules now. link --> Is __init__.py not required for packages in Python 3.3+

I believe you will have to add the {full path}/src and {full path}/auto directories to the PYTHONPATH to provide python scripts the proper pathing, or you can use the python sys module and use sys.path inside your modules to set your pathing for the module you would like to import link --> https://docs.python.org/3/tutorial/modules.html#the-module-search-path

import sys
# example path could be "C:/Users/Bob/Desktop/project/auto"
sys.path.append("{full path to your auto directory}/auto")
Nolan Walker
  • 352
  • 1
  • 7
  • Yeah, I do not need __init__.py files, that is correct although not sure how to programatically achieve what you are referring to with sys.path. Can you please elaborate? – Ben Muller May 29 '21 at 05:51
  • the sys.path programmatically adds the provided path *directory tree* to the PYTHONPATH. So you have the option to manually add it to the pathing or use python code to do it for you. – Nolan Walker May 29 '21 at 18:31