1

When I run launch.py it fails and when I run main.py directly it works. launch.py just imports and runs main.py. Why?

├── dir
│   ├── bla.py
│   ├── __init__.py
│   └── main.py
├── __init__.py
└── launch.py

launch.py
---------
    #!/usr/bin/env python
    # -*- coding: utf-8 -*-

    from dir import main
    main.main()

main.py
-------

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    import bla
    bla.pront()


bla.py
------

def pront():
    print('pront')

EDITED:

enter image description here

jorgesumle
  • 21
  • 6
  • Since Python 3, you have to import `bla` like this: `import .bla` because it's relative to the current module. – Jean-François Fabre Sep 05 '16 at 20:44
  • python3 launch.py Traceback (most recent call last): File "launch.py", line 4, in from dir import main File "/home/jorge/Desktop/module_test/dir/main.py", line 3 import .bla ^ SyntaxError: invalid syntax – jorgesumle Sep 05 '16 at 20:54

2 Answers2

1

Using your layout and with the following files, we don't have problems.

launch.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from dir import main

if __name__ == "__main__":
   main. main()

main.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
    from . import bla
except:
    import bla

def main():
    bla.pront()

if __name__ == "__main__":
    main()

The try ... except structure is used in case the main.py was used inside or outside the package.

Of course, there is a lot of info about it. You can start with this.

Community
  • 1
  • 1
Jose Raul Barreras
  • 849
  • 1
  • 13
  • 19
-1

I believe I see the answer...
You have not defined main, perhaps try that. The reason why it works when called directly is because Python scripts are run in the order in which functions appear unless a specific function is called.

Try changing main.py to

import bla
def mainfunction():
    bla.pront()

Then change launch.py to

import main
main.mainfunction()

I hope this helps! :)

ALinuxLover
  • 458
  • 3
  • 10
  • Your changes doesn't work: python3 launch.py Traceback (most recent call last): File "launch.py", line 4, in import main ImportError: No module named 'main'. I changed the import to `import dir.main` and also doesn't work. Traceback (most recent call last): File "launch.py", line 4, in import dir.main File "/home/jorge/Desktop/module_test/dir/main.py", line 3, in import bla ImportError: No module named 'bla' – jorgesumle Sep 05 '16 at 21:00