简体   繁体   English

导入错误:无法导入名称 - Python

[英]ImportError: cannot import name - Python

I am trying to import some variables from a different python file resides in the same directory from a another python file.我试图从另一个 python 文件中导入位于同一目录中的不同python文件中的一些变量。

I have two files in the same directory as below:在同一目录中有两个文件如下所示:

constantvariables.py

test.py

This is how constantvariables.py looks like这就是constantvariables.py样子

class CONST(object):
    FOO = 1234
    NAMESPACE = "default"
    DEPLOYMENT_NAME = "deployment-test"
    DOCKER_IMAGE_NAME = "banukajananathjayarathna/bitesizetroubleshooter:v1"
    SERVICE_CLUSTER = "deployment-test-clusterip"
    SERVICE_NODEPORT = "deployment-test-nodeport"
    INGRESS_NAME = "deployment-test-ingress"

    def __setattr__(self, *_):
        pass

CONST = CONST()

and this is how my test.py looks like:这就是我的test.py样子:

import os 
from . import constantvariables


print(constantsvariables.NAMESPACE)

But I get this error:但我收到此错误:

Traceback (most recent call last): File "test.py", line 7, in from .回溯(最近一次通话):文件“test.py”,第 7 行,来自 . import constantsvariables ImportError: cannot import name 'constantsvariables'导入常量变量导入错误:无法导入名称“常量变量”

can someone please help me?有人可以帮帮我吗?

Python version I am using python 2.7.5 Python 版本我使用的是python 2.7.5

Make constant file like that constant.py and put inside config folder for proper management.制作像constant.py这样的常量文件并放在config文件夹中以进行适当的管理。

FOO = 1234
NAMESPACE = "default"
DEPLOYMENT_NAME = "deployment-test"
DOCKER_IMAGE_NAME = "banukajananathjayarathna/bitesizetroubleshooter:v1"
SERVICE_CLUSTER = "deployment-test-clusterip"
SERVICE_NODEPORT = "deployment-test-nodeport"
INGRESS_NAME = "deployment-test-ingress"

Inside your base directory create main.py file and call the constant inside that.在您的基本目录中创建 main.py 文件并在其中调用常量。

import os 
from config.constants import NAMESPACE, FOO
print(NAMESPACE)

If you want to keep your constant file as it is, you can write this:如果你想保持你的常量文件原样,你可以这样写:

import os 
from constantvariables import CONST

print(CONST.NAMESPACE)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM