I have the following folder structure.
project/
sandbox.py
module/
__init__.py
klass.py
__init__.py
has the following:
from klass import Klass
if __name__ == '__main__':
'do stuff'
This works fine. sandbox.py
looks like this:
from module import *
if __name__ == '__main__":
'do similar stuff'
On the command line, while in the project
directory:
$ python module/__init__.py
# things work correctly
$ python sandbox.py
Traceback (most recent call last):
File "sandbox.py", line 1, in <module>
from module import *
File "/Uses/chuck/.../project/module/__init__.py, line 1 in <module>
from klass import Klass
ImportError: No module named 'klass'
I think this might have to do with relative imports, and tried changing from klass import Klass
to from .klass import Klass
, but that didn't work either.
My goal is, from files outside the module, to be able to use from module import *
or from module import Klass
. What do I need to do?
In case it matters, this is with Python 3.5.2 under macOS within a virtual environment.
Use absolute path and __main__.py
file for this:
from module.klass import Klass
'do stuff'
In __init__.py
:
from .klass import Klass
Now you can execute it as follows:
$ python sandbox.py
do similar stuff
$ python -m module
do somthing
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.