【问题标题】:Use project config variables across different Python scripts在不同的 Python 脚本中使用项目配置变量
【发布时间】:2020-05-16 19:37:19
【问题描述】:

我正在处理一个包含多个目录的项目,每个目录都有许多 python 脚本。它涉及使用某些 关键参数 我使用 yaml 配置文件传递。

目前使用的方法是,(我会说它很天真)它只是将 yaml 解析为 python 字典,然后将其导入其他脚本并访问值。

据我所知,有:

  1. Abseil 库,可用于跨不同脚本访问标志,但使用起来很麻烦。
  2. 使用类(最好是单例)的另一种方法,将所有全局变量放入其中并在其他脚本中公开该类的实例。

我想问一下,有没有其他库可以用于此目的?处理它的最pythonic方法是什么?

任何帮助将不胜感激。谢谢!

【问题讨论】:

  • 感觉这个问题比较适合https://codereview.stackexchange.com/
  • @anuragal 我没有提到任何代码,所以我怀疑.. 我正在寻找的只是可用于在项目中跨 python 脚本共享变量的可能方法......如果您能分享一些东西,我将不胜感激!

标签: python python-3.x configuration global-variables


【解决方案1】:

为了使全局值可以跨模块访问,我使用了类(单例)方法。

我下面列出的代码也在我的 Gisthub https://gist.github.com/auphofBSF/278206afff675cd30377f4894a5b2b1d

我的通用 GlobalValues 单例类和用法如下。此类位于主目录下的子目录中。在我还附加的使用示例中,我将 GlobalValues 类放在文件夹 myClasses 中的文件 globals.py

class GlobalValues:
    """
    a Singleton class to serve the GlobalValues
    USAGE: (FirstTime)
    from myClasses.globals import GlobalValues
    global_values = GlobalValues()
    global_values.<new value> = ...
    ... = global_values.<value>

    USAGE: (Second and n'th time, in same module or other modules)
        NB adjust `from myClasses.globals` dependent on relative path to this module 
    from myClasses.globals import GlobalValues 
    global_values = GlobalValues.getInstance()
    global_values.<new value> = ...
    ... = global_values.<value>


    """
    __instance = None
    DEFAULT_LOG_LEVEL="CRITICAL"

    @staticmethod
    def get_instance():
        """ Static access method. """
        if GlobalValues.__instance == None:
            GlobalValues()
        return GlobalValues.__instance
    def __init__(self):
        """ Virtually private constructor. """
        if GlobalValues.__instance != None:
            raise Exception("This class is a singleton! once created use global_values = Glovalvalues.get_instance()")
        else:
            GlobalValues.__instance = self

我的使用示例如下

示例文件布局

        <exampleRootDir>
            Example_GlobalValues_Main.py  #THIS is the main 
            myClasses # A folder
                globals.py #for the singleton class GlobalValues 
                exampleSubModule.py # demonstrates use in submodules

Example_GlobalValues_Main.py

print(
    """ 
        ----------------------------------------------------------
        Example of using a singleton Class as a Global value store
        The files in this example are in these folders

        file structure:
        <exampleRootDir>
            Example_GlobalValues_Main.py  #THIS is the main 
            myClasses # A folder
                globals.py #for the singleton class GlobalValues 
                exampleSubModule.py # demonstrates use in submodules
        -----------------------------------------------------------
    """
)

from myClasses.globals import GlobalValues

globalvalues = GlobalValues() # THe only place an Instance of GlobalValues is created

print(f"MAIN: global DEFAULT_LOG_LEVEL is {globalvalues.DEFAULT_LOG_LEVEL}")
globalvalues.DEFAULT_LOG_LEVEL = "DEBUG"
print(f"MAIN: global DEFAULT_LOG_LEVEL is now {globalvalues.DEFAULT_LOG_LEVEL}")

#Add a new global value:
globalvalues.NEW_VALUE = "hello"

#demonstrate using global modules in another module
from myClasses import exampleSubModule

print(f"MAIN: globalvalues after opening exampleSubModule are now {vars(globalvalues)}")

print("----------------- Completed -------------------------------")

exampleSubModule.py如下,位于myClasses文件夹中


"""
Example SubModule using the GlobalValues Singleton Class
"""
# observe where the globals module is in relation to this module . = same directory
from .globals import GlobalValues

# get the singleton instance of GlobalValues, cannot instantiate a new instance
exampleSubModule_globalvalues = GlobalValues.get_instance() 

print(f"exampleSubModule: values in GlobalValues are: {vars(exampleSubModule_globalvalues)}")

#Change a value
exampleSubModule_globalvalues.NEW_VALUE = "greetings from exampleSubModule"  
#add a new value
exampleSubModule_globalvalues.SUBMODULE = "exampleSubModule"

【讨论】:

  • 不错!感谢您的详细回答。我认为使用 Class 方法是有意义的,因为它简单且易于访问变量。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-10-17
  • 1970-01-01
  • 2010-10-07
  • 2021-11-12
  • 2013-03-20
  • 2015-10-04
  • 2016-03-23
相关资源
最近更新 更多