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.

87 lines
2.8 KiB

6 years ago
6 years ago
6 years ago
6 years ago
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. "type": type}
  27. if default != None:
  28. self.__flags[alias]["hasDefault"] = True
  29. self.__parser.add_argument("-%s" % shortFlag,
  30. "--%s" % longFlag,
  31. help=help,
  32. type=type,
  33. default=default)
  34. def addInstanceDirArg(self):
  35. self.__instanceDirArgSet = True
  36. self.addArg(alias="datasetDir", shortFlag="d", longFlag="dataset_dir",
  37. help="the base direcotry of the dataset; if this flag is given the others can be omitted",
  38. type=str, ignoreDatabaseConfig=True)
  39. def parse(self):
  40. self.__parsedArgs = {}
  41. args = vars(self.__parser.parse_args())
  42. if self.__instanceDirArgSet:
  43. self.__config = readConfig(os.path.join(args["dataset_dir"],
  44. "dataset.config"))
  45. self.__parseDatasetConfig()
  46. for alias, flag in self.__flags.items():
  47. self.__parsedArgs[alias] = self.__processFlag(args, flag)
  48. self.__config = None
  49. return self.__parsedArgs
  50. def __parseDatasetConfig(self):
  51. for flag, value in self.__config["STRUCTURE"].items():
  52. self.__parsedArgs[flag] = value
  53. def __processFlag(self, args, flag):
  54. longFlag = flag["longFlag"]
  55. tmpValue = self.__parsedArgs[longFlag] if longFlag in self.__parsedArgs else None
  56. if flag["ignoreDatabaseConfig"] == True:
  57. tmpValue = None
  58. if args[longFlag]:
  59. tmpValue = args[longFlag]
  60. if tmpValue == None:
  61. tmpValue = flag["type"](input("pass arguement %s: " % longFlag))
  62. return tmpValue