简体   繁体   English

如何在python中的文件之间传递全局变量

[英]How to pass global variables between files in python

I have a semi-large python app that runs on linux. 我有一个在Linux上运行的半大型python应用程序。 I am trying to set it up so that i can read a config file at program startup and then save those values for use at any time while the application is running, without re-reading the config file. 我正在尝试进行设置,以便我可以在程序启动时读取配置文件,然后保存这些值以在应用程序运行时随时使用,而无需重新读取配置文件。

So I am trying to load a configValues class in my first modual, test.py. 因此,我尝试在第一个模态test.py中加载configValues类。 And read the values set. 并读取设置的值。 Then in this example read the values again in test2.py. 然后在此示例中,再次读取test2.py中的值。

I never get the values. 我永远都不会得到价值观。 Can someone help me? 有人能帮我吗?

Config.py Config.py

class config():

    def __init__(self):
        configFile = File(myPath)
        if configFile.exist():
            myXML = str(configFile.openAndRead())

    def setupValues(self):
        configValues.color = self.getElement('color')

    def getElement(self, element):
        tree=et.fromstring(self.myXML)

        for el in tree.findall('head'):
            for ch in el.findall(element):
            return ch.text


class configValues():

    def __init__(self):
        global color

test.py test.py

import config

class test():

    def __init__(self):
        configObj = config.Config()
        configVal = config.configValues()

        configObj.setupValues()
        print configVal.color

test2.py test2.py

import config

class test2():

    def __init__(self):
        configVal = config.configValues()

        print configVal.color

Add a global variable and a function to your config.py. 在您的config.py中添加一个全局变量和一个函数。 And rather than creating configobj in test1.py and test2.py, you can call this function to get the config object. 您可以调用此函数以获取config对象,而不是在test1.py和test2.py中创建configobj

configobj = None

def getconfigobj():
  global configobj
  if not configobj:
    configObj = config.Config()
  return configobj

Edit as per comment. 根据评论进行编辑。 Does something like the following help(using a single instance for the class)?:- 是否有以下类似的帮助(为类使用单个实例)?

config.py

 class config():
        _instance = None
        def __new__(cls):
            if config._instance:
                return config._instance
            return super(config, cls).__new__(cls)


        def __init__(self, myPath):
            configFile = File(myPath)
            if configFile.exist():
                myXML = str(configFile.openAndRead())
            config._dict['instance'] = self

        def setupValues(self):
            self.color = self.getElement('color')

        def getElement(self, element):
            tree=et.fromstring(self.myXML)

            for el in tree.findall('head'):
                for ch in el.findall(element):
                return ch.text

test1.py

import config
class test():
    def __init__(self):
        configObj = config.Config()
        configObj.setupValues()
        print configObj.color

test2.py

import config
class test2():
    def __init__(self):
        configObj = config.Config()
        print configObj.color

I would not use global variables in this case. 在这种情况下,我不会使用全局变量。 You may want to assign the config values as config properties and use it like so: config.py 您可能希望将config值分配为config属性并按如下方式使用它:config.py

class Config:
    def __init__(self):
        # property of the config class
        self.color = 'my default color'
        # open your config file ..

    def setup_values(self):
        # assign new value
        self.color = self.get_color()

    def get_color(self):
        # get values from config xml file ..
        return "red"

And then import the config in other module and call the color property: main.py 然后将配置导入其他模块,并调用color属性:main.py

from config import Config

class Main:
    def __init__(self):
        config = Config()
        config.setup_values()
        color = config.color
        print color

Main()

I would also shorten the code with one method less by getting the config values in the constructor instead in additional method "setup_values" like so: 通过在构造函数中获取配置值,而不是在其他方法“ setup_values”中,我还将减少一种方法的代码,如下所示:

class Config:
    def __init__(self):
        # property of the config class
        self.color = self.get_color()

    def get_color(self):
        # open your config file ..
        # get values from config xml file ..
        return "red"

and the main.py should look like: 并且main.py应该看起来像:

from config import Config

class Main:
    def __init__(self):
        config = Config()
        color = config.color
        print color

Main()

Bear in mind that it is not a good practice to use global variables in your code so the suggested code above may do the job for you. 请记住,在代码中使用全局变量不是一个好习惯,因此上面建议的代码可能会对您有所帮助。

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

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