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:
run.py .flaskenv requirements.txt /app | - __init__.py | - bot.py | - /strategies | - __init__.py | - strategy1.py
run.py looks something like this:
from flask import Flask from app.bot import test_func ...
bot.py looks something like this:
import strategies as st strategy = st.Strat1 ... def test_func(): pass
/strategies/__init__.py looks like this:
from .strategy1 import Strat1
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:
ModuleNotFoundError: No module named 'strategies'
Okay… So I try changing the imports, I change bot.py to:
from strategies import * strategy = Strat1 ...
Same issue. I try one more time, imports now look like this:
from .strategies import * strategy = Strat1 ...
Works perfectly fine now during ‘flask run’, hooray!…
Except, now, when I run the file directly, I get:
Traceback (most recent call last): File "app/bot.py", line 4, in <module> from .strategies import * ImportError: attempted relative import with no known parent package
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
import sys import os SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.dirname(SCRIPT_DIR))
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
import sys import os SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.dirname(SCRIPT_DIR))
In bot.py, I changed my import based on the comment from evanstjabadi :
from app import strategies as st
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:
if __name__ == '__main__': import sys import os SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.dirname(SCRIPT_DIR)) from app import strategies as st ...
Not sure if it’s the cleanest fix, but it’s now working in both cases!