Properties file in python (similar to Java Properties)

后端 未结 25 2782
故里飘歌
故里飘歌 2020-11-29 17:41

Given the following format (.properties or .ini):

propertyName1=propertyValue1
propertyName2=propertyValue2
...
propertyNam         


        
25条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-29 18:47

    This is what i had written to parse file and set it as env variables which skips comments and non key value lines added switches to specify hg:d

    • -h or --help print usage summary
    • -c Specify char that identifies comment
    • -s Separator between key and value in prop file
    • and specify properties file that needs to be parsed eg : python EnvParamSet.py -c # -s = env.properties

      import pipes
      import sys , getopt
      import os.path
      
      class Parsing :
      
              def __init__(self , seprator , commentChar , propFile):
              self.seprator = seprator
              self.commentChar = commentChar
              self.propFile  = propFile
      
          def  parseProp(self):
              prop = open(self.propFile,'rU')
              for line in prop :
                  if line.startswith(self.commentChar)==False and  line.find(self.seprator) != -1  :
                      keyValue = line.split(self.seprator)
                      key =  keyValue[0].strip() 
                      value = keyValue[1].strip() 
                              print("export  %s=%s" % (str (key),pipes.quote(str(value))))
      
      
      
      
      class EnvParamSet:
      
          def main (argv):
      
              seprator = '='
              comment =  '#'
      
              if len(argv)  is 0:
                  print "Please Specify properties file to be parsed "
                  sys.exit()
              propFile=argv[-1] 
      
      
              try :
                  opts, args = getopt.getopt(argv, "hs:c:f:", ["help", "seprator=","comment=", "file="])
              except getopt.GetoptError,e:
                  print str(e)
                  print " possible  arguments  -s  -c < comment char >     \n  Try -h or --help "
                  sys.exit(2)
      
      
              if os.path.isfile(args[0])==False:
                  print "File doesnt exist "
                  sys.exit()
      
      
              for opt , arg  in opts :
                  if opt in ("-h" , "--help"):
                      print " hg:d  \n -h or --help print usage summary \n -c Specify char that idetifes comment  \n -s Sperator between key and value in prop file \n  specify file  "
                      sys.exit()
                  elif opt in ("-s" , "--seprator"):
                      seprator = arg 
                  elif opt in ("-c"  , "--comment"):
                      comment  = arg
      
              p = Parsing( seprator, comment , propFile)
              p.parseProp()
      
          if __name__ == "__main__":
                  main(sys.argv[1:])
      

提交回复
热议问题