Reputation: 529
I am developing small app with few submodules:
src/
setup.py
myapp/
myGuiapp.py
modules/
__init__.py
editorGui.py
fileParser.py
modules/__ init __.py
from editorGui import editorWindow
from fileParser import parseMyFile
myGuiapp.py
from modules import editorWindow
from modules import parseMyFile
parseMyFile(parms)
editorWindow(self)
EditorGui.py
from fileParser import parseMyFile
# from .fileParser import parseMyFile
# from modules.fileParser import parseMyFile
fileParser(parms)
I would like to have my EditorGui.py to be called from myGuiapp.py but also to be able to run it by itself. How should i setup relative importing in such case ?
If in EditorGui.py I will set :
from modules.fileParser import parseMyFile
>python editorGui.py
ModuleNotFoundError: No module named 'modules'
but from main app
>python myGuiapp.py
OK !
If in EditorGui.py I will set :
from .fileParser import parseMyFile
>python EditorGui.py
ModuleNotFoundError: No module named '__main__.fileParser'; '__main__' is not a package
If in EditorGui.py I will set :
from fileParser import parseMyFile
>python editorGui.py
OK !
>python myGuiapp.py
ModuleNotFoundError: No module named 'fileParser'
How can I make both work and what i am doing wrong here? I would like to avoid setting up ABSOLETE paths to this dev directory. What would be most pythonic and clean way to structure such app ?
EDIT: After @Diego Trazzi post, I've decided to move my EditorGui.py up the level:
src/
setup.py
myapp/
myGuiapp.py
editorGui.py
modules/
__init__.py
fileParser.py
This solves many issues but for curiosity, my question still stands. How can I import module from same level while being imported by code from parent directory?
Upvotes: 0
Views: 533
Reputation: 560
To avoid specifying the relative path to the modules You could append to your file the path:
# yourfile.py
import sys
sys.path.insert(0, '/path/to/application/app/folder')
You could also specify it in the shell from which you run the command:
python [-bBdEiOQsRStuUvVWxX3?] [-c command | -m module-name | script | - ] [args]
https://docs.python.org/2/using/cmdline.html
Ideally your project should be structured in such way so all the
package_name/
/* setup.py and other misc files */
package_name/
__init__.py
/* module files go here */
test/
/* tests go here */
So that your executables reside in the top level and when you distribute your project users will not have to dig into sub folders. I have found this answer very helpful:
Upvotes: 2