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

command.py 4.3 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. # Copyright 2020 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ============================================================================
  15. """Command module."""
  16. import sys
  17. import os
  18. import argparse
  19. from importlib import import_module
  20. import mindinsight
  21. from mindinsight.utils.log import setup_logger
  22. from mindinsight.utils.exceptions import MindInsightException
  23. class BaseCommand:
  24. """Base command class."""
  25. name = ''
  26. description = ''
  27. # logger for console output instead of built-in print
  28. console = None
  29. # logger for log file recording in case audit is required
  30. logfile = None
  31. def add_arguments(self, parser):
  32. """
  33. Add arguments to parser.
  34. Args:
  35. parser (ArgumentParser): specify parser to which arguments are added.
  36. """
  37. def update_settings(self, args):
  38. """
  39. Update settings.
  40. Args:
  41. args (Namespace): parsed arguments to hold customized parameters.
  42. """
  43. def run(self, args):
  44. """
  45. Implementation of command logic.
  46. Args:
  47. args (Namespace): parsed arguments to hold customized parameters.
  48. """
  49. raise NotImplementedError('subclasses of BaseCommand must provide a run() method')
  50. def invoke(self, args):
  51. """
  52. Invocation of command.
  53. Args:
  54. args (Namespace): parsed arguments to hold customized parameters.
  55. """
  56. error = None
  57. try:
  58. self.update_settings(args)
  59. except MindInsightException as e:
  60. error = e
  61. self.console = setup_logger('mindinsight', 'console', console=True, logfile=False, formatter='%(message)s')
  62. if error is not None:
  63. self.console.error(error.message)
  64. sys.exit(1)
  65. self.logfile = setup_logger('scripts', self.name, console=False, logfile=True)
  66. self.run(args)
  67. def main():
  68. """Entry point for mindinsight CLI."""
  69. console = setup_logger('mindinsight', 'console', console=True, logfile=False, formatter='%(message)s')
  70. if (sys.version_info.major, sys.version_info.minor) < (3, 7):
  71. console.error('Python version should be at least 3.7')
  72. sys.exit(1)
  73. permissions = os.R_OK | os.W_OK | os.X_OK
  74. # set umask to 0o077
  75. os.umask(permissions << 3 | permissions)
  76. parser = argparse.ArgumentParser(
  77. prog='mindinsight',
  78. description='MindInsight CLI entry point (version: {})'.format(mindinsight.__version__),
  79. allow_abbrev=False)
  80. parser.add_argument(
  81. '--version',
  82. action='version',
  83. version='%(prog)s ({})'.format(mindinsight.__version__))
  84. subparsers = parser.add_subparsers(
  85. dest='cli',
  86. title='subcommands',
  87. description='the following subcommands are supported',
  88. )
  89. commands = {}
  90. scripts_path = os.path.realpath(os.path.join(__file__, os.pardir, os.pardir, 'scripts'))
  91. files = os.listdir(scripts_path)
  92. files.sort()
  93. for file in files:
  94. if file.startswith('_') or not file.endswith('.py'):
  95. continue
  96. module = import_module('mindinsight.scripts.{}'.format(file[:-len('.py')]))
  97. command_cls = getattr(module, 'Command', None)
  98. if command_cls is None or not issubclass(command_cls, BaseCommand):
  99. continue
  100. command = command_cls()
  101. command_parser = subparsers.add_parser(command.name, help=command.description, allow_abbrev=False)
  102. command.add_arguments(command_parser)
  103. commands[command.name] = command
  104. argv = sys.argv[1:]
  105. if not argv or argv[0] == 'help':
  106. argv = ['-h']
  107. args = parser.parse_args(argv)
  108. cli = args.__dict__.pop('cli')
  109. command = commands[cli]
  110. command.invoke(args)