Reputation: 634
I've been trying to figure out how to get imported modules to work in my python script. It works in pycharm, so I know it's something with the path configuration when I try to run it in a unix terminal.
Running on ubuntu I get this: Traceback (most recent call last):
File "main_app.py", line 12, in <module>
from flask_app.python_scripts import canvas_test
ModuleNotFoundError: No module named 'flask_app'
Is there a command I need to run from the terminal or something that I need to add to my python script?
Upvotes: 1
Views: 5781
Reputation: 187
Your directory structure needs to be set up so that both flask_app.py and main_app.py are in the same directory.
$ ls
flask_app.py main_app.py __pycache__
Contents of the files...
<flask_app.py>
def canvas_test():
return "canvas test print"
<main_app.py>
from flask_app import canvas_test
canvas = canvas_test()
print(canvas)
When you run you get...
$ python main_app.py
canvas test print
If what you are importing isn't in the same directory then you need to use a relative import statement e.g.
from ..flask_app import canvas_test
or include your module in your PYTHONPATH
Upvotes: 1
Reputation: 23079
What we do at my company is have an init.py file in each directory that contains Python utility scripts. The scripts do import init to read this file. This file modifies the python path to include the paths to our utility library and some third party libraries. Since everything is in the same source tree, the init.py file uses the location of itself to turn relative paths into absolute paths. Here's one of our such files:
import sys, os
inletPath = os.path.dirname(__file__) + "/../../.."
sys.path.append(inletPath + "/common/python")
sys.path.append(inletPath + "/inletfetch/common/common-pyutil")
sys.path.append(inletPath + "/inletfetch/common/common-pyutil/thirdparty")
inletPath is the root of our source tree. The specific paths are computed relative to the source root
We don't try to share these files across directories. We just put one in any directory containing any python scripts that we execute directly.
The great thing about this is that all you have to do when you create a new script is add "import init" at the start of it, before importing anything else, and all the other stuff will get found.
Upvotes: 1