#! /usr/bin/env python """This script retrieves the value of a PARAMETER tag from either a MODEL or a PLATFORM in one XML file. Usage: get_ece_config_param.py XML MODEL|PLATFORM PARAMETER Example #1, retrieve the number of processor for IFS: get_ece_config_param.py config-run.xml IFS NUMPROC Example #2, retrieve the 'run dir' on the 'bi' platform, defined in the config-run.xml: get_ece_config_param.py config-run.xml bi RUN_DIR If not found or error, returns nothing and exits with return code 1. """ from xml.etree import ElementTree, ElementInclude import xml.sax from io import StringIO import sys import os if __name__ == "__main__": if len(sys.argv) != 4: sys.stderr.write( "Must pass THREE arguments! Usage:") sys.stderr.write( " get_ece_config_param.py XMLFILE MODEL|PLATFORM PARAMETER") sys.exit(1) f = sys.argv[1] modelname = sys.argv[2] paramname = sys.argv[3] # -- PARSE FILE parser = xml.sax.make_parser() try: tree = ElementTree.parse(f) except IOError: sys.stderr.write( "Could not open file: %s\n" % f) sys.exit(1) except ElementTree.ParseError, v: row, column = v.position print "error on row", row, "column", column, ":", v sys.exit(1) except: sys.stderr.write( "Could not parse XML file: %s\n"+f) sys.exit(1) root = tree.getroot() ElementInclude.include(root) s = unicode(ElementTree.tostring(root)) io = StringIO(s) parser.parse(io) # -- Get list of PARAMETER, first assuming it is a MODEL, if not it is a PLATFORM Params=[tag.findall('Parameter') for tag in root.findall('Model') if tag.get('name')==modelname] if not Params: Params=[tag.findall('Parameter') for tag in root.findall('Platform') if tag.get('name')==modelname] # -- Return value if Params: val=[k.find('Value').text for k in Params[0] if k.get('name') == paramname ] else: val=None if val: sys.stdout.write( val[0] ) else: sys.stderr.write("Parameter '%s' or Model/Platform '%s' not found.\n" % (paramname,modelname)) sys.exit(1)