代码之家  ›  专栏  ›  技术社区  ›  Steven Hepting

为python程序存储设置的官方方式是什么?

  •  47
  • Steven Hepting  · 技术社区  · 16 年前

    Django使用真实的python文件进行设置,trac使用.ini文件,其他一些软件使用XML文件保存这些信息。

    这些方法中的一种比另一种更受guido和/或python社区的祝福吗?

    12 回复  |  直到 7 年前
        1
  •  28
  •   lprsd    16 年前

    取决于主要的目标受众。

    如果是程序员更改了文件,只需使用像settings.py这样的python文件即可。

    如果是最终用户,那么考虑一下ini文件。

        2
  •  29
  •   Matthias Vanpoecke brianz    10 年前

    正如许多人所说,没有“正式”的方式。然而,有许多选择。有 a talk at PyCon 今年有很多可用的选项。

        3
  •  14
  •   Zippo    14 年前

    我用架子( http://docs.python.org/library/shelve.html ):

    shelf = shelve.open(filename)
    shelf["users"] = ["David", "Abraham"]
    shelf.sync() # Save
    
        4
  •  13
  •   drdaeman    16 年前

    不知道这是否可以被视为“官方”,但它在标准库中: 14.2. ConfigParser — Configuration file parser .

    显然,这是, 不过,这是一个普遍的解决方案。只要使用对任务最合适的东西,而不需要任何必要的复杂性(尤其是图灵完整性)。考虑一下自动或GUI配置器)。

        5
  •  8
  •   jhufford    16 年前

    还有一个选择,Pyqt。Qt有一种与平台无关的方法来存储Qsettings类的设置。在引擎盖下面,在Windows上,它使用注册表,在Linux中,它将设置存储在一个隐藏的conf文件中。qsettings工作得很好,而且很不平整。

        6
  •  6
  •   Shane C. Mason    16 年前

    我不确定是否有一种“正式”的方式(这在python的禅中没有提到):我倾向于自己使用config解析器模块,我认为您会发现这很常见。比起python文件方法,我更喜欢这种方法,因为您可以写回它,并根据需要动态地重新加载。

        7
  •  5
  •   Cobry    8 年前

    据我所知,没有什么好的解决办法。没有正确或错误的方法来存储应用程序设置,只要您能接受,XML、JSON或所有类型的文件都是好的。对于我个人使用的python pypref 这很简单,跨平台和简单。

    pypref非常有用,因为它可以存储静态和动态设置和首选项…

        from pypref import Preferences
    
        #  create singleton preferences instance
        pref = Preferences(filename="preferences_test.py")
    
        # create preferences dict
        pdict = {'preference 1': 1, 12345: 'I am a number'}
    
        # set preferences. This would automatically create preferences_test.py 
        # in your home directory. Go and check it.
        pref.set_preferences(pdict)
    
        # lets update the preferences. This would automatically update 
        # preferences_test.py file, you can verify that. 
        pref.update_preferences({'preference 1': 2})
    
        # lets get some preferences. This would return the value of the preference if
        # it is defined or default value if it is not.
        print pref.get('preference 1')
    
        # In some cases we must use raw strings. This is most likely needed when
        # working with paths in a windows systems or when a preference includes
        # especial characters. That's how to do it ...
        pref.update_preferences({'my path': " r'C:\Users\Me\Desktop' "})
    
        # Sometimes preferences to change dynamically or to be evaluated real time.
        # This also can be done by using dynamic property. In this example password
        # generator preference is set using uuid module. dynamic dictionary
        # must include all modules name that must be imported upon evaluating
        # a dynamic preference
        pre = {'password generator': "str(uuid.uuid1())"}
        dyn = {'password generator': ['uuid',]}
        pref.update_preferences(preferences=pre, dynamic=dyn)
    
        # lets pull 'password generator' preferences twice and notice how
        # passwords are different at every pull
        print pref.get('password generator')
        print pref.get('password generator')
    
        # those preferences can be accessed later. Let's simulate that by creating
        # another preferences instances which will automatically detect the 
        # existance of a preferences file and connect to it
        newPref = Preferences(filename="preferences_test.py")
    
        # let's print 'my path' preference
        print newPref.get('my path')
    
        8
  •  3
  •   Kamil Kisiel    16 年前

    这在很大程度上取决于您的配置有多复杂。如果您正在进行一个简单的键值映射,并且您希望能够使用文本编辑器编辑设置,那么我认为ConfigParser是一种可行的方法。

    如果您的设置很复杂,包括列表和嵌套数据结构,那么我将使用XML或JSON并创建一个配置编辑器。

    对于非常复杂的事情,如果最终用户不希望更改太多的设置,或者更可信,只需创建一组Python类并评估一个Python脚本来获取配置。

        9
  •  2
  •   dbader    12 年前

    对于我喜欢使用OS环境变量的Web应用程序: os.environ.get('CONFIG_OPTION')

    这对于不同部署之间的设置尤其有效。您可以在这里阅读更多关于使用env vars背后的基本原理: http://www.12factor.net/config

    当然,这只对只读值有效,因为对环境的更改通常不是持久的。但如果您不需要写访问,它们是一个非常好的解决方案。

        10
  •  2
  •   Eric Aya    7 年前

    最简单的使用方法之一是使用 json 模块。 将文件保存到 config.json 详情如下。

    在JSON文件中保存数据:

    {
    
        "john"  : {
            "number" : "948075049" , 
            "password":"thisisit" 
        }    
    }
    

    从JSON文件读取:

    import json
    
    #open the config.json file 
    
    with open('config.json') as f:
        mydata = json.load(f) ; 
    
    #Now mydata is a python dictionary 
    
    print("username is " , mydata.get('john').get('number') , " password is " , mydata.get('john').get('password')) ;
    
        11
  •  0
  •   SilentGhost    16 年前

    为什么吉多会祝福一些超出他能力范围的事情?不,没有什么特别的祝福。

        12
  •  0
  •   Checksum    16 年前

    更方便。没有正式的方法。但是使用XML文件是有意义的,因为它们可以被各种其他应用程序/库操纵。