0

I have the following directory structure:

- src
    - __init__.py
    - scripts
        - __init__.py
        - preprocessing.py
    - project1
        - main.py
    - project2
        - main.py

I'm trying to access the script(s) inside the scripts folder from within both the main.py files.

I've tried adding in the __init__.py (blank) files, and importing with import scripts, from src import scripts, and from .. import scripts. None of these seem to work.

I either get: ValueError: Attempted relative import in non-package, or no module found.

Thanks in advance!


P.S. I assume that the directory structure will get deeper soon (e.g. multiple subdirectories within scripts and project1 / project2). So if these is an easy way to deal with this as well, that would be very much appreciated.

Oliver Crow
  • 334
  • 6
  • 14
  • Appears to be a duplicate to this question https://stackoverflow.com/questions/4383571/importing-files-from-different-folder – Zack Tarr Feb 07 '18 at 13:35
  • What version of Python are you using? Is the directory that contains `src` in your `sys.path`? – PM 2Ring Feb 07 '18 at 13:59
  • I'm using 2.7.10. I tried adding it to my `sys.path` but not change really. Also, I've heard that using the `__init__.py` means you don't have to change your `sys.path` as it can be imported as a package. – Oliver Crow Feb 07 '18 at 14:03

1 Answers1

0

One way to deal with that (albeit not the cleanest one) is to manually add the root directory to the sys.path variable so that python can look for modules in it, for example, in your main.py you may add these lines at the top:

#/src/project1/main.py
import os
import sys
sys.path.append(os.getcwd() + '\\..\\')  # this is the src directory

This will allow python to look for modules in the directory above the one running the script, and this will work:

import scripts.preprocessing

Keep in mind that python will only look for modules in the same directory or below as the script is running. If you start /src/project2/main.py, python doesn't know anything about /src/project1/ or /src/scripts/

Vince
  • 36
  • 1
  • 4
  • Thanks for the reply. I was trying to avoid adding this to every file that wants access to the `scripts` – Oliver Crow Feb 09 '18 at 11:20
  • You can also add the lines to the __init__.py of a directory, all the python files in that directory should then have access to the scripts. – Vince Feb 09 '18 at 14:36
  • Could you provide an example of one of these lines in the `init.py` please? – Oliver Crow Feb 10 '18 at 19:21