I'm starting a project in python, the code structure now as below:
project/
__init__.py
a.py
b.py
mainA.py
utilities/
__init__.py
mainB.py
c.py
The __init__
files are all blank.
I want to run utilities/mainB.py
as a program(using something like python main.py
), and mainB needs to import a.py
and b.py
. So I tried from .. import a
and some other approaches, but the import
failed. The error information is:
ValueError: Attempted relative import in non-package
So here comes the questions:
mainB.py
so it can be run as a main program?mainA.py
can be run as main program now, it also imports a.py
and b.py
(using import a
and import b
).
I think the code structure may become more complex. Say, if mainA.py
has to import a module from project/some/directory
, how can I do that?You could use Python's built-in module-running functionality (python -m <module>
).
python -m project.utilities.mainB
This allows you to write mainB normally as part of the package, so relative and absolute imports will both work correctly.
For an in-depth discussion of this functionality, see PEP-338.