JS.
JS.

Reputation: 16097

Output persistent data in valid python

Background:
I would like to import peristent configuration data for a Python model from a file. I would like to avoid using xml, json, pickle, et. al. because:

My goal is to allow users to create simple configurations for my model by writing simple Python dictionaries. My model will then import the dictionary and go.

My models are created dynamically based on the underlying hardware, so I would like my model to also be able to generate a default dictionary and write it out (to a file) as Python code for the user to update/change.

Question:
How can I output simple Python objects, such as simple dictionaries as Python code?

Disclaimers:
For those folks that want to citing security reason for not doing this, yes, I know the risks of importing Python code directly. These models are used in a restricted, private corporate environment (i.e. hardware development group) and require specialized, non-public hardware to run. My users have direct access to the hardware and root access, so borking my models is the least satisfactory way of getting fired and/or arrested.

Reference: https://stackoverflow.com/a/23587727/310399

Upvotes: 0

Views: 92

Answers (2)

Bob
Bob

Reputation: 704

If configuration is what you're after. You may want to look into ConfigParser or ConfigObj. It just relies on simple ini files which are pretty much human readable text. From there you can have the program interpret the necessary data. Config files look like so:

[Section 1]
option1 = value1
option2 = value2

[Section 2]
option1 = value1
option2 = value2

From there you can just read it in like so:

options = ConfigParser()
options.read(file)

Options will then be treated similar to a dictionary. You can then write these out as well using:

with open(file, "w+") as fs:
    options.write(fs)

Upvotes: 1

g.d.d.c
g.d.d.c

Reputation: 47978

You're trying to programmatically generate a module with default values that your users can modify? Something like this may work:

defaults = dict(val1="val1", val2=3)
varname = 'MyModuleConfig'
with open('myconfig.py', 'w') as fh:
  fh.write('%s = %s\n' % (varname, repr(defaults)))
  # Produced file should contain :
  # MyModuleConfig = {'val2': 3, 'val1': 'val1'}

Upvotes: 1

Related Questions