Frage

I have been wanting to define variables in Python by reading them from a simple text file. Therefore I have done some reading on ConfigParser, ConfigObj, PyYaml and JSON. At the moment I am particularly interested in ConfigObj and 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. 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:

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. Therefore I would like to know whether PyYaml and/or ConfigObj have an in-built function to achieve the above?

War es hilfreich?

Lösung

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?

Andere Tipps

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top