Changeset 5916


Ignore:
Timestamp:
09/14/21 15:08:53 (3 years ago)
Author:
omamce
Message:

O.M. : swith from obsolete library getopt

to argparse

File:
1 edited

Legend:

Unmodified
Added
Removed
  • TOOLS/MOSAIX/update_xml.py

    r4195 r5916  
     1#!/usr/bin/env python 
    12### =========================================================================== 
    23### 
     
    2526# 
    2627import xml.etree.ElementTree 
    27 import getopt, sys 
    28  
    29 ## 
    30 def usage () : 
    31     texte = """%(prog)s usage : 
    32 python %(prog)s [-d] [-i iodef.xml] [-o iodef_new.xml] -n <node in Xpath syntax> -k <key>  -v <value> 
    33 python %(prog)s [-d] [-i iodef.xml] [-o iodef_new.xml] -n <node in Xpath syntax> -t <value> 
    34  -d         | --debug         : debug 
    35  -i <file>  | --input=<file>  : input file  (default: iodef.xml) 
    36  -o <file>  | --output=<file> : output file (default: overwrite input file) 
    37  -n <node>  | --node=<node>   : node in Xpath syntax 
    38  -f <field> | --field=<field> : xml field to update 
    39  -v <value> | --value=<value> : new value for xml field 
    40  -t <text>  | --text=<text>   : will replace the 'text' part of the Xpath by <text> 
    41 examples :   
    42     python %(prog)s -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="file_src"]/field[@id="mask_source"]' -k name -v maskutil_T 
    43     python %(prog)s -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="dia"]/variable[@name="dest_grid"]'   -t ${dstDomainType} 
    44     """ 
    45     #print ( texte % ( sys.argv[0], sys.argv[0], sys.argv[0], sys.argv[0] ) ) 
    46     #print ( texte %   ( 6*[sys.argv[0]] )) 
    47     print ( texte % { 'prog':sys.argv[0] } ) 
     28import argparse, sys, textwrap 
    4829     
    4930# Check version of Python 
     
    5435  sys.exit (1) 
    5536   
    56 ## Default input parameters 
    57 FileIn   = 'iodef.xml' 
    58 FileOut  = None 
    59 Node     = None  
    60 Key      = None 
    61 Text     = None 
    62 Value    = None 
    63 Debug    = False 
     37# Creating a parser to read the command line arguments 
     38# The first step in using the argparse is creating an ArgumentParser object: 
     39parser = argparse.ArgumentParser (description = """ 
     40examples :  
     41     python %(prog)s -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="file_src"]/field[@id="mask_source"]' -k name -v maskutil_T 
     42     python %(prog)s -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="dia"]/variable[@name="dest_grid"]'   -t dstDomainType 
     43     python %(prog)s -i iodef.xml -e commands.txt (not implemented yet) 
     44   """ + "\n" + "SVN : " + __Revision__, formatter_class=argparse.RawDescriptionHelpFormatter, epilog='-------- This is the end of the help message --------') 
    6445 
    65 ## Command line options 
    66 try: 
    67     myopts, myargs = getopt.getopt ( sys.argv[1:], 'i:o:n:k:v:t:dh', [ 'input=', 'output=', 'node=', 'key=', 'value=', 'text=', 'debug=', '--help' ] ) 
    68 except getopt.GetoptError as cmdle : 
    69     print ( "Command line error : "+cmdle ) 
    70     usage () 
    71     sys.exit(1) 
     46# Adding arguments 
     47group1 = parser.add_mutually_exclusive_group (required=True) 
    7248 
    73 for myopt, myval in myopts : 
    74     if myopt in [ '-h', '--help'   ] : usage () ; sys.exit (0) ;  
    75     if myopt in [ '-i', '--input'  ] : FileIn   = myval 
    76     if myopt in [ '-o', '--output' ] : FileOut  = myval 
    77     if myopt in [ '-n', '--node'   ] : Node     = myval 
    78     if myopt in [ '-k', '--key'    ] : Key      = myval 
    79     if myopt in [ '-t', '--text'   ] : Text     = myval 
    80     if myopt in [ '-v', '--value'  ] : Value    = myval 
    81     if myopt in [ '-d', '--debug'  ] : Debug    = True 
     49parser.add_argument ( '-i', '--input'  , help="input file"            , default='iodef.xml', type=str, metavar='<input_file>' ) 
     50parser.add_argument ( '-o', '--output' , help="output file"           , default=None       , type=str, metavar='<output_file>'  ) 
     51parser.add_argument ( '-n', '--node'   , help="xml node in Xpath syntax", default=None, required=True, type=str, metavar='<xml_node>') 
     52group1.add_argument ( '-k', '--key'    , help="xml key to update"     , default=None , type=str , metavar='<xml_key>' ) 
     53group1.add_argument ( '-t', '--text'   , help="will replace the 'text' part of the Xpath by <text>", default=None, type=str, metavar='<text>' ) 
     54parser.add_argument ( '-v', '--value'  , help="new value for xml key", default=None, type=str, metavar='<value>' ) 
     55parser.add_argument ( '-d', '--debug'  , action="store_true", default=False ) 
     56parser.add_argument ( '-V', '--verbose', action="store_true", default=False ) 
    8257 
    83 ## Some coherency checking of command line parameters 
    84 ErrorCount = 0 
     58# Parse command line 
     59myargs = parser.parse_args() 
     60Verbose  = myargs.verbose 
    8561 
    86 if FileIn == None : 
    87     print ( "Error : please specify input file by -i <file>" ) 
    88     ErrorCount += 1 
     62if Verbose : print ( "Command line arguments : " , myargs ) 
    8963 
    90 if Node == None : 
    91     print ( "Error : please specify -n <node>" ) 
    92     ErrorCount += 1 
    93      
    94 if Key == None and Text == None : 
    95     print ( "Error : please specify either -t <text> or -k <key> -v <value>" ) 
    96     ErrorCount += 1 
     64FileIn   = myargs.input 
     65FileOut  = myargs.output 
     66Node     = myargs.node 
     67Key      = myargs.key 
     68Text     = myargs.text 
     69Value    = myargs.value 
     70Debug    = myargs.debug 
    9771 
    98 if Key != None and Text != None : 
    99     print ( "Error : please specify only one option between -t "+Text+" and -k "+Key ) 
    100     ErrorCount += 1 
    101  
     72# Error handling not dealed by argparse 
    10273if Key != None and Value == None : 
    103     print ( "Error : please specify -v <value> when -k "+Key+" is given") 
    104     ErrorCount += 1 
    105   
    106 if ErrorCount > 0 : 
    107     usage () 
    108     sys.exit (1) 
     74    print ( "Error. When -k|--key=<key> is specified, you must specify -v|--value=<xml_value>" ) 
     75    sys.exit -1) 
    10976 
    11077if FileOut == None : FileOut = FileIn 
    11178 
    112 ## Remove white spaces at beginning and end of line 
     79# Remove whitespaces at both ends 
    11380Node = Node.rstrip().lstrip() 
    11481 
     
    12087 
    12188## Check that one and only one node is found 
    122 if len(nodeList) == 0 : 
     89if len (nodeList) == 0 : 
    12390    print ( "Error : node not found" ) 
    124     print ( "Node  : "+Node ) 
     91    print ( "Node  : " + Node ) 
    12592    sys.exit (1) 
    12693     
    127 if len(nodeList) > 1 : 
    128     print ( "Error : "+len(nodeList)+" occurences of node found" ) 
    129     print ( "Node  : "+Node ) 
    130     sys.exit (1) 
     94if len (nodeList) > 1 : 
     95    print ( "Error : " + len (nodeList)+" occurences of node found" ) 
     96    print ( "Node  : " + Node ) 
     97    sys.exit (2) 
    13198 
    13299## Update element 
     
    134101 
    135102if Debug : 
    136     print ( 'Node  : '+Node  ) 
    137     print ( 'Key   : '+Key   ) 
    138     print ( 'Value : '+Value ) 
     103    print ( 'Node  : ' + Node  ) 
     104    print ( 'Key   : ' + Key   ) 
     105    print ( 'Value : ' + Value ) 
    139106 
    140107if Text != None : 
    141108    if Debug : 
    142         print ( 'Attributes of node: '+str(elem.attrib) ) 
    143         print ( 'Text              : '+str(elem.text)   ) 
     109        print ( 'Attributes of node: ' + str (elem.attrib) ) 
     110        print ( 'Text              : ' + str (elem.text)   ) 
    144111    elem.text = Text 
    145112 
     
    147114    # To do : check that Key exist (it is added if not : do we want that ?) 
    148115    if Debug : 
    149         print ( 'Attributes of node: '+str(elem.attrib) ) 
     116        print ( 'Attributes of node: ' + str (elem.attrib) ) 
    150117    elem.attrib.update ( { Key:Value } ) 
    151118     
    152  
    153119## Writes XML tree to file 
    154120iodef.write ( FileOut ) 
Note: See TracChangeset for help on using the changeset viewer.