Adafe Jaja
Adafe Jaja

Reputation: 53

Importing module from parent folder subfolder to run in scripts subfolder [siblings]

My project structure looks like this:

project/
|--- helper_modules/
    |--- util.py
|--- scripts/
    |--- A.py

If I put the script A.py in the project/ folder, it runs and imports successfully using from helper_modules.util import fn. But I have a number of scripts and to keep things organised I'd like to have them all in their own subfolder. How can I do this and still import from helper_modules?

I'm in the directory /project/ when I call the scripts.

Upvotes: 0

Views: 157

Answers (3)

Daniel Pryden
Daniel Pryden

Reputation: 60957

If your current directory is /project/, you should launch the script using:

python -m scripts.A

And from within scripts/A.py, you can do

from helper_modules.util import fn

Upvotes: 0

amitoz
amitoz

Reputation: 323

You just need add this in your script A.py :

from ..helper_modules.util import fn

and run A.py exiting one level from the project folder, so if you are in project folder do:

cd ..

Then run A.py using

python -m project.scripts.A

Upvotes: 1

Adafe Jaja
Adafe Jaja

Reputation: 53

I found this which gave me a workaround. Apparently this can't be done by default in Python.

In each script in the scripts folder, I started with this code:

# add to the Python path to import helper functions
import sys
import os
sys.path.append(os.path.abspath('.'))

Upvotes: 0

Related Questions