From 8ffdca7ec095f73f7527e2756fe732ae8bef231a Mon Sep 17 00:00:00 2001 From: Ben Brown Date: Wed, 9 Dec 2015 17:19:13 +0000 Subject: Add and make use of small python library for yarns Due to an unwillingness to add another IMPLEMENTS that copypasta'd the same "MATCH_n = os.environ['MATCH_n']", add this small library in an attempt to reduce the amount of repitition. Change-Id: I64dc67ad7bd4c0d7572906168c72b0628a7574db --- yarns.webapp/yarnlib.py | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 yarns.webapp/yarnlib.py (limited to 'yarns.webapp/yarnlib.py') diff --git a/yarns.webapp/yarnlib.py b/yarns.webapp/yarnlib.py new file mode 100644 index 0000000..89f87d9 --- /dev/null +++ b/yarns.webapp/yarnlib.py @@ -0,0 +1,47 @@ +# Copyright (C) 2015 Codethink Limited +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; version 2 of the License. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +# Python library for lorry-controller yarns. + +import os +import json + +DATADIR = os.environ['DATADIR'] + +def matches(): + '''Returns a generator of MATCH_n environment variables.''' + matches = {} + prefix = "MATCH_" + + for key, value in os.environ.iteritems(): + if key.startswith(prefix): + stripped_key = key[len(prefix):] + if stripped_key.isdigit() and stripped_key != "0": + matches[int(stripped_key)] = value + + for key in sorted(matches): + if key != 1 and key-1 not in matches: + break + yield matches[key] + +def load_json_from_file(filename): + '''Deserialise json file.''' + with open(filename, "r") as f: + return json.load(f) + +def dump_json_to_file(j, filename): + '''Write serialised object to file.''' + with open(filename, "w") as f: + return json.dump(j, f, indent=4) -- cgit v1.2.1