Python - Doing absolute imports from a subfolder

前端 未结 3 2422
鱼传尺愫
鱼传尺愫 2021-02-20 01:56

Basically I\'m asking the same question as this guy: How to do relative imports in Python?

But no one gave him a correct answer. Given that you are inside a subfolder an

相关标签:
3条回答
  • 2021-02-20 02:28
    main.py
    setup.py
    app/ ->
        __init__.py
        package_a/ ->
           __init__.py
           module_a.py
        package_b/ ->
           __init__.py
           module_b.py
    
    1. You run python main.py.
    2. main.py does: import app.package_a.module_a
    3. module_a.py does import app.package_b.module_b

    Alternatively 2 or 3 could use: from app.package_a import module_a

    That will work as long as you have app in your PYTHONPATH. main.py could be anywhere then.

    So you write a setup.py to copy (install) the whole app package and subpackages to the target system's python folders, and main.py to target system's script folders.

    0 讨论(0)
  • 2021-02-20 02:33

    If I'm reading correctly, in Python 2.5 or higher:

    from ..Module_B import Module_B
    

    I thought I was well-versed in Python but I had no idea that was possible in version 2.5.

    0 讨论(0)
  • 2021-02-20 02:39

    If you are then importing Module_B in to App, you would

    Module_B.py: import ModuleA

    App.py (which also imports ModuleA which is now by default in your Pythonpath)

    import Module_B.Module_B
    

    Another alternative, is to update __init__.py (the one in Module_A/App folder) to:

    import os
    import sys
    sys.path.extend('%s../' % os.getcwd())
    import ModuleA
    

    Another alternative, is to add your folder to the PYTHONPATH environment var.

    0 讨论(0)
提交回复
热议问题