I have a python project/library called "slingshot" with the following directory structure:
slingshot/
__init__.py
__main__.py
build.py
deploy.py
util/
__init__.py
prepare_env.py
cdn_api.py
From __main__.py
I would like to import functions from util/prepare_env.py
.
I would like to ensure that util
refers to the util
I have in my project, and not some other util
library that may be installed somewhere.
I tried from .util import prepare_env
but I get an error.
from util import prepare_env
seems to work, but doesn't address the ambiguity of "util".
What am I doing wrong?
__main__.py
is as follows:
import os
from .util import prepare_env
if __name__ == '__main__':
if 'SLINGSHOT_INITIALIZED' not in os.environ:
prepare_env.pip_install_requirements()
prepare_env.stub_travis()
prepare_env.align_branches()
os.environ['SLINGSHOT_INITIALIZED'] = 'true'
When I type python3 ./slingshot
I get the following error:
File "./slingshot/__main__.py", line 2, in <module>
from .util import prepare_env
ImportError: attempted relative import with no known parent package
When I type python3 -m ./slingshot
I get the following error:
/usr/local/opt/python3/bin/python3.6: Relative module names not supported
__main__.py
modules in a package make the module run as a script when you use the -m
command line switch. That switch takes a module name, not a path, so drop the ./
prefix:
python3 -m slingshot
The current working directory is added to the start of the module search path so slingshot
is found first, no need to give a relative path specification here.
From the -m
switch documentation:
Search
sys.path
for the named module and execute its contents as the__main__
module.Since the argument is a module name, you must not give a file extension (
.py
). The module name should be a valid absolute Python module name[.][...]
As with the
-c
option, the current directory will be added to the start ofsys.path
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With