Python: modules and packaging - why isn't __init__.py file executed before __main__.py?

后端 未结 3 1664
暖寄归人
暖寄归人 2021-01-04 07:56

I have a python program that is entirely contained in a directory with the following structure:

myprog/
├── __init__.py
├── __main__.py
├── moduleone.py
└──          


        
相关标签:
3条回答
  • 2021-01-04 08:21

    So, having looked at the other responses and not being thrilled, I tried:

    from __init__ import *
    

    from my __main__.py file.

    I suppose it doesn't allow you to refer to the module by name, but for simple cases it seems to work.

    0 讨论(0)
  • 2021-01-04 08:26

    Do I have to import these functions into __main__ somehow?

    Yes. Only items in builtins are available without an import. Something like:

    from myprog import func1, func2
    

    should do the trick.

    If you don't have myprog installed in the normal python path then you can work around it with something like:

    import sys
    import os
    path = os.path.dirname(sys.modules[__name__].__file__)
    path = os.path.join(path, '..')
    sys.path.insert(0, path)
    from myprog import function_you_referenced_from_init_file
    

    Which, quite frankly, is horrid.

    I would suggest going with MartijnPieters suggestion and put the -m on the command line, in which case __main__.py can look like:

    from myprog import function_you_referenced_from_init_file
    
    0 讨论(0)
  • 2021-01-04 08:28

    The __init__.py is only loaded when you are import the package. You are instead treating the directory as a script, by executing the directory.

    You can still treat the package as a script, instead of the directory however. To both treat the directory as a package and as the main script, by using the -m switch:

    python -m myprog
    
    0 讨论(0)
提交回复
热议问题