Skip to content

Instantly share code, notes, and snippets.

@FlyingJester
Created December 3, 2017 09:22
Show Gist options
  • Save FlyingJester/13973de121c13522b1c23ea57900a5a9 to your computer and use it in GitHub Desktop.
Save FlyingJester/13973de121c13522b1c23ea57900a5a9 to your computer and use it in GitHub Desktop.
Configuration utility, to run in a different process.
#!/bin/python
# Copyright (c) 2017 Martin McDonough
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
import json
import os
from sys import stdin
from tempfile import NamedTemporaryFile
conf_filename = "conf.json"
# If the file doesn't already exist, create it with an empty object insie it.
if not os.path.isfile(conf_filename):
conf_file = open(conf_filename, "wb")
conf_file.write("{}\n")
conf_file.close()
conf = {}
else:
conf_file = open(conf_filename, "rb")
conf = json.load(conf_file)
conf_file.close()
buffer = ""
while 1:
c = stdin.read(1)
if c == '\n':
line = buffer
# Trim away any newline
if line[-1] == '\n':
line = line[:-1]
at = line.find('=')
# if an equals was found, then this is an assignment
if at != -1:
# Split the input at the equals. Everything before it is the key,
# everything after is the value.
key = line[:at]
value = line[at+1:]
is_number = True
is_float = False
for c in value:
if c == '.':
is_float = True
elif not c.isdigit():
is_number = False
break
if is_number:
if is_float:
value = float(value)
else:
value = int(value)
elif value == "true":
value = True
elif value == "false":
value = False
conf[key] = value
# Write the results to a temporary file. This way if we crash or
# something, we don't clobber the existing conf.
temp_conf_file = NamedTemporaryFile(delete = False)
json.dump(conf, temp_conf_file, indent=4)
temp_conf_file.close()
# Writing successful, now overwrite the conf file with the temp file.
os.rename(temp_conf_file.name, conf_filename)
else:
# This was not an assignment, return the value
value = conf[line]
if type(value) == type(True):
if value:
value = "true"
else:
value = "false"
else:
value = str(value)
print (line + "=" + value)
buffer = ""
else:
buffer += c.lower()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment