How to reference python package when filename contains a period

前端 未结 5 377
一生所求
一生所求 2020-12-03 02:51

I am using django and I have a file named models.admin.py and I want to do the following idea in models.py:

from \"models.admin\" import *

5条回答
  •  执笔经年
    2020-12-03 03:18

    Actually, you can import a module with an invalid name. But you'll need to use imp for that, e.g. assuming file is named models.admin.py, you could do

    import imp
    with open('models.admin.py', 'rb') as fp:
        models_admin = imp.load_module(
            'models_admin', fp, 'models.admin.py',
            ('.py', 'rb', imp.PY_SOURCE)
        )
    

    But read the docs on imp.find_module and imp.load_module before you start using it.

提交回复
热议问题