claudiadast
claudiadast

Reputation: 611

Error when importing module from a different folder in the same parent directory

I have the following python package structure:

rkstr8/cloud/batch.py
rkstr8/profiling/test.py

I'm trying to import a class called BatchJobListStatusPoller from batch.py into test.py, but it gives me the error: ModuleNotFoundError: No module named 'rkstr8' when I run this import statement in test.py:

from rkstr8.cloud.batch import BatchJobListStatusPoller

The rkstr8/ folder, as well as the cloud/ and profiling/ sub-folders all have an __init__.py.

What am I doing wrong here?

Upvotes: 1

Views: 439

Answers (1)

Karl
Karl

Reputation: 1724

The problem is because Python only imports modules from directories/subdirectories of wherever you run your program python test.py. It also searches for modules in the sys.path variable which includes the standard library ones and any installed from pip. I can think of two ways to solve this problem, one is the more standard way and one is more of an unorthodox workaround.

  1. The first way would be to have a script directly in the aws-sfn-tutorial folder maybe called start_test.py. Its sole purpose is to call your test.py script upon starting up and pass any command line arguments down.
    This will allow your test.py script to then be able to correctly find all the python modules inside the aws-sfn-tutorial folder.

  2. The second way would be to modify the sys.path variable in test.py to add in the path to the file you want to import.

    • You can either specify a relative path ../ which moves it one folder up relative to the current path
    • Or you can specify the absolute path to the folder

Example of 2:

import sys
sys.path.append('../') # Or use the absolute path here instead

# After adding to sys.path import your module
from cloud.batch import BatchJobListStatusPoller 

Upvotes: 1

Related Questions