1

I am building on AWS CodeBuild using Python 2.7, but I believe this is much more a generic python import problem. I have a directory setting, shown below. I am running test.py inside the test folder. I would like to import the dependency mainScript.py as part of this testing. However, I cannot seem to get the relative dependencies right and I am having a lot of difficulty importing the mainScript within the test folder. Below is a layout of my directory folder

main
    src
       mainScript.py
    test
       test.py

If for example my directory setup was something like

main
    test
       test.py
       mainScript.py

I could have my import be done the following way

from mainScript import *

I have confirmed this works. But, I like it in its own src folder. I have tried all these These are the following relative path attempts I have tried

from ..src/mainScript import * #SyntaxError: invalid syntax
from ..src.mainScript import * #ValueError: attempted relative import beyond top-level package
from mainScript import * #ModuleNotFoundError: No module named 'mainScript'
from src.mainScript import * #ModuleNotFoundError: No module named 'src'
from src/mainScript import * #SyntaxError: invalid syntax   

I have been struggling for a bit and I couldn't quite find a question with someone asking about accessing a brother/sister folder script. Thank you in advance for your help.

applecrusher
  • 5,508
  • 5
  • 39
  • 89

2 Answers2

2

Python treats directories as packages if they contain a __init__.py file. Updating your structure to the following should do the trick:

    __init__.py
    src
       __init__.py
       mainScript.py
    test
       __init__.py
       test.py

Now, from test.py, you could do from ..src import *. For more details on init.py, you can look here: What is __init__.py for?

Bogsan
  • 631
  • 6
  • 12
0

In addition to adding the init.py files. It ended up being that I had to run python with the -m argument in my command, which was added in Python 2.4.

PEP 338

Python 2.4 adds the command line switch -m to allow modules to be located using the Python module namespace for execution as scripts. The motivating examples were standard library modules such as pdb and profile, and the Python 2.4 implementation is fine for this limited purpose.

So the command to launch from the top directory is:

python -m test.test

This seems to work and get the right namespace. Then in your test.py file you would import the mainScript the following way

from src.mainScript import *
applecrusher
  • 5,508
  • 5
  • 39
  • 89