2

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.

WoJ
  • 27,165
  • 48
  • 180
  • 345
  • Seems to work for me in Python 2. – Brian Huey Oct 21 '16 at 15:19
  • Does my [similar question](http://stackoverflow.com/questions/39528736/how-do-you-organise-a-python-project-that-contains-multiple-packages-so-that-eac) help? – Pod Oct 28 '16 at 12:52

1 Answers1

0

you should set in hello.py

import lib.helper

and in the call of do something method:

lib.helper.something()

That solves your problem, you can call main or hello without problems

aperezfals
  • 1,341
  • 1
  • 10
  • 26