Skip to content

Add labconfig.{save,load}_appconfig() #48

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 45 additions & 1 deletion labscript_utils/labconfig.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,11 @@
# for the full license. #
# #
#####################################################################
import sys
import os
import configparser
from ast import literal_eval
from pprint import pformat
from pathlib import Path

from labscript_utils import dedent
from labscript_profile import default_labconfig_path, LABSCRIPT_SUITE_PROFILE
Expand Down Expand Up @@ -69,3 +71,45 @@ def __init__(
not have the required keys. Make sure the config file containes the
following structure:\n{self.file_format}"""
raise Exception(dedent(msg))


def save_appconfig(filename, data):
"""Save a dictionary as an ini file. The keys of the dictionary comprise the section
names, and the values must themselves be dictionaries for the names and values
within each section. All section values will be converted to strings with
pprint.pformat()."""
# Error checking
for section_name, section in data.items():
for name, value in section.items():
try:
valid = value == literal_eval(pformat(value))
except (ValueError, SyntaxError):
valid = False
if not valid:
msg = f"{section_name}/{name} value {value} not a Python built-in type"
raise TypeError(msg)
data = {
section_name: {name: pformat(value) for name, value in section.items()}
for section_name, section in data.items()
}
c = configparser.ConfigParser(interpolation=None)
c.optionxform = str # preserve case
c.read_dict(data)
Path(filename).parent.mkdir(parents=True, exist_ok=True)
with open(filename, 'w') as f:
c.write(f)


def load_appconfig(filename):
"""Load an .ini file and return a dictionary of its contents. All values will be
converted to Python objects with ast.literal_eval(). All keys will be lowercase
regardless of the written contents on the .ini file."""
c = configparser.ConfigParser(interpolation=None)
c.optionxform = str # preserve case
# No file? No config - don't crash.
if Path(filename).exists():
c.read(filename)
return {
section_name: {name: literal_eval(value) for name, value in section.items()}
for section_name, section in c.items()
}