简体   繁体   English

使用ConfigObj或PyYaml将字典对提取到交互式工作区

[英]Extract dictionary pairs into the interactive workspace using ConfigObj or PyYaml

I have been wanting to define variables in Python by reading them from a simple text file. 我一直想通过从简单的文本文件中读取变量来在Python中定义变量。 Therefore I have done some reading on ConfigParser, ConfigObj, PyYaml and JSON. 因此,我在ConfigParser,ConfigObj,PyYaml和JSON上做了一些阅读。 At the moment I am particularly interested in ConfigObj and PyYaml. 目前我对ConfigObj和PyYaml特别感兴趣。 However I have not managed yet to do what I would like to do in a clean manner. 但是,我还没有完成我想以干净的方式做的事情。

With ConfigObj and PyYaml I can load everything defined in an external text file into a dictionary. 使用ConfigObj和PyYaml,我可以将外部文本文件中定义的所有内容加载到字典中。 I would like to proceed with this dictionary by extracting all key-value pairs and storing them as separate variables into my interactive workspace. 我想通过提取所有键值对并将它们作为单独的变量存储到我的交互式工作区来继续这个词典。

This is the PyYaml way I have been using thus far: 这是我到目前为止使用的PyYaml方式:

import yaml

config_file = open('myFile', 'r')
config = yaml.read(config_file)

keys = config.keys()
values = config.values()

for i in range(len(keys)):
    string = keys[i] + '=' + str(values[i])
    eval(string)

Using eval is sometimes frowned about due to possibly allowing all sorts of malicious things to happen. 使用eval有时会因为可能允许发生各种恶意事件而感到不满。 Therefore I would like to know whether PyYaml and/or ConfigObj have an in-built function to achieve the above? 因此,我想知道PyYaml和/或ConfigObj是否具有内置函数来实现上述功能?

The following should do what you want, assuming I understand your question correctly. 假设我正确理解你的问题,以下应该做你想要的。

Note: I check for the existence of the key before overwriting it and instead put it under a slightly different name otherwise. 注意:我在覆盖它之前检查是否存在密钥,而是将其置于稍微不同的名称之下。

import yaml

config_file = open('myFile', 'r')
config = yaml.read(config_file)

keys = config.keys()
values = config.values()

for key,val in zip(keys,values):
    if key not in locals():
        locals()[key] = val
    else:
        locals()[key+"_yaml"] = val

While this works, I would actually suggest you just stick to having a dictionary with your values in them. 虽然这有效,但我实际上建议你坚持使用带有你的价值观的字典。 What's wrong with just referencing a dictionary if a local variable doesn't exist? 如果本地变量不存在,只引用字典有什么问题?

If you 如果你

import __main__

then you can 那么你也能

__main__.__dict__[keys[i]] = values[i]

or even 甚至

__main__.__dict__.update(config)

Whether that is wise or not depends a lot on how much you value being surprised when your global functions are overwritten by yaml entries. 这是否明智取决于当您的全局函数被yaml条目覆盖时,您感到惊讶的程度。

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

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