本文介绍了当文件名包含句点时,如何引用python包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用django,我有一个名为models.admin.py的文件,我想在models.py中执行以下想法:

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 *

但是,我收到语法错误有双引号。但是,如果我只是从models.admin导入

however, I get a syntax error for having double quotes. But if I just do

from models.admin import *

然后我得到ImportError:没有名为admin的模块

then I get "ImportError: No module named admin"

有没有办法从python文件导入在其名称中有一个句点?

Is there any way to import from a python file that has a period in its name?

推荐答案

实际上,你可以导入一个无效的模块名称。但是您需要使用为此,例如假设文件名为 models.admin.py ,您可以

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.

这篇关于当文件名包含句点时,如何引用python包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 09:28