You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

86 lines
2.7 KiB

6 years ago
  1. import configparser
  2. import os
  3. import argparse
  4. def readConfig(configFilePath):
  5. config = configparser.ConfigParser()
  6. if os.path.isfile(configFilePath):
  7. config.read(configFilePath)
  8. return config
  9. class ArgParser:
  10. def __init__(self):
  11. self.__flags = {}
  12. self.__parser = argparse.ArgumentParser()
  13. self.__instanceDirArgSet = False
  14. self.__config = None
  15. self.__parsedArgs = {}
  16. def addArg(self, alias,
  17. shortFlag,
  18. longFlag,
  19. help,
  20. type,
  21. default=None,
  22. ignoreDatabaseConfig=False):
  23. self.__flags[alias] = {"longFlag": longFlag,
  24. "hasDefault": False,
  25. "ignoreDatabaseConfig": ignoreDatabaseConfig}
  26. if default != None:
  27. self.__flags[alias]["hasDefault"] = True
  28. self.__parser.add_argument("-%s" % shortFlag,
  29. "--%s" % longFlag,
  30. help=help,
  31. type=type,
  32. default=default)
  33. def addInstanceDirArg(self):
  34. self.__instanceDirArgSet = True
  35. self.addArg(alias="datasetDir", shortFlag="d", longFlag="dataset_dir",
  36. help="the base direcotry of the dataset; if this flag is given the others can be omitted",
  37. type=str, ignoreDatabaseConfig=True)
  38. def parse(self):
  39. self.__parsedArgs = {}
  40. args = vars(self.__parser.parse_args())
  41. if self.__instanceDirArgSet:
  42. self.__config = readConfig(os.path.join(args["dataset_dir"],
  43. "dataset.config"))
  44. self.__parseDatasetConfig()
  45. for alias, flag in self.__flags.items():
  46. self.__parsedArgs[alias] = self.__processFlag(args, flag)
  47. self.__config = None
  48. return self.__parsedArgs
  49. def __parseDatasetConfig(self):
  50. for flag, value in self.__config["STRUCTURE"].items():
  51. self.__parsedArgs[flag] = value
  52. def __processFlag(self, args, flag):
  53. longFlag = flag["longFlag"]
  54. tmpValue = self.__parsedArgs[longFlag] if longFlag in self.__parsedArgs else None
  55. if flag["ignoreDatabaseConfig"] == True:
  56. tmpValue = None
  57. if args[longFlag]:
  58. tmpValue = args[longFlag]
  59. if tmpValue == None:
  60. tmpValue == input("pass arguement %s: " % longFlag)
  61. return tmpValue