Skip to content
Advertisement

ModuleNotFoundError for python flask app. Script works during import OR direct execution but never both

I’ve got a problem with imports I just can’t seem to find the answer to. I am using python 3, and have all the correct libraries installed. My file structure looks something like this:

JavaScript

run.py looks something like this:

JavaScript

bot.py looks something like this:

JavaScript

/strategies/__init__.py looks like this:

JavaScript

Where Strat1 in strategy1.py is simply a class.


As it stands, when I run bot.py directly, it works perfectly fine.

The problem arises when I start my flask app, I then receive the error:

JavaScript

Okay… So I try changing the imports, I change bot.py to:

JavaScript

Same issue. I try one more time, imports now look like this:

JavaScript

Works perfectly fine now during ‘flask run’, hooray!…

Except, now, when I run the file directly, I get:

JavaScript

I am at a loss… I can either run the file directly with success and then importing it doesn’t work. Or I can import it just fine but no longer run it directly.

I have attempted the common fix of

JavaScript

and every variation of that, to no avail.

Any ideas?

Advertisement

Answer

Looks like it was a bit of a combination of everything.

Ultimately, what I ended up doing was this:

In run.py, I included the path adding before any other imports

JavaScript

In bot.py, I changed my import based on the comment from evanstjabadi :

JavaScript

At this point, running/importing the script from flask works correctly.

To get the script working when running directly, I added this at the very top:

JavaScript

Not sure if it’s the cleanest fix, but it’s now working in both cases!

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement