I have a script hello.py
which can be used as a module by main.py
, or be called from the command line. It itself imports a module helper.py
which is in the same directory:
├── lib
│ ├── hello.py
│ ├── helper.py
│ ├── __init__.py
├── main.py
The contents of the files are
$ cat main.py
import lib.hello
lib.hello.sayhi()
------------------------------------
$ cat lib/hello.py
import helper
def sayhi():
print("bonjour")
print(helper.something())
if __name__ == "__main__":
print("hello")
------------------------------------
$ cat lib/helper.py
def something():
print("something")
The problem I have is that hello called from the command line works fine (imports helper.py
correctly as it is at the same leval as hello.py
) but when running main.py I get
$ python3 main.py
Traceback (most recent call last):
File "main.py", line 1, in <module>
import lib.hello
File "/tmp/lib/hello.py", line 1, in <module>
import helper
ImportError: No module named 'helper'
because from the perspective of main.py
, helper.py
is in lib
.
If I change the import in hello.py
to import lib.helper
then I have the same problem the other way round:
$ python3 hello.py
Traceback (most recent call last):
File "hello.py", line 1, in <module>
import lib.helper
ImportError: No module named 'lib'
How do I get out of this catch 22 situation?
I suspect that the information from "PEP 338 -- Executing modules as scripts" could be useful but I fail to understand how to bring them in practice to my problem.