Relative importing python module from a subfolder from a different subfolder

前端 未结 2 1801
死守一世寂寞
死守一世寂寞 2021-02-15 15:21

I\'m trying to use alembic which is an sqlalchemy tool in python. You type a command and it generates a folder \"alembic\" with py files inside. The py file inside, needs to lin

2条回答
  •  时光说笑
    2021-02-15 15:51

    You have two possible solutions to your problem:

    Modify your PYTHONPATH environment variable

    Add the path to apps catalogue by running following BASH / SH shell commands in your terminal:

    $ export PYTHONPATH=$PYTHONPATH:'/path/to/apps'
    

    Please not that adding it to the PATH environment variable won't work. To find out more about PYTHONPATH, how to manage it plus nice and friendly info on modules in general:

    http://www.stereoplex.com/blog/understanding-imports-and-pythonpath

    Please note however that this approach does affect your system's PYTHONPATH. It is highly recommended to use a virtualenv - just in case things go wrong, it won't affect all your system and other apps. When using virtualenvwrapper:

    $ add2virtualenv '/path/to/apps'
    

    More HERE.

    Append path from inside the Python script

    Alternatively, you can do the same but just for a script runtime by adding:

    import sys
    sys.path.append('/path/to/apps')
    

    to your apps/alembic/env.py file.

    Finally, in same file, make a following change:

    from myapp.configs.config import DefaultConfig
    

    And please note that your apps/myapp folder should also contain __init__.py file (might be empty) to make Python to treat is as a module as Demian Brecht pointed out.

提交回复
热议问题