arg.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. # copyright (c) 2024 PaddlePaddle Authors. All Rights Reserve.
  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. import os
  15. import shlex
  16. class CLIArgument(object):
  17. """ CLIArgument """
  18. def __init__(self, key, *vals, quote=False, sep=' '):
  19. super().__init__()
  20. self.key = str(key)
  21. self.vals = [str(v) for v in vals]
  22. if quote and os.name != 'posix':
  23. raise ValueError(
  24. "`quote` cannot be True on non-POSIX compliant systems.")
  25. self.quote = quote
  26. self.sep = sep
  27. def __repr__(self):
  28. return self.sep.join(self.lst)
  29. @property
  30. def lst(self):
  31. """ lst """
  32. if self.quote:
  33. vals = [shlex.quote(val) for val in self.vals]
  34. else:
  35. vals = self.vals
  36. return [self.key, *vals]
  37. def gather_opts_args(args, opts_key):
  38. """ gather_opts_args """
  39. def _is_opts_arg(arg):
  40. return arg.key == opts_key
  41. args = sorted(args, key=_is_opts_arg)
  42. idx = None
  43. for i, arg in enumerate(args):
  44. if _is_opts_arg(arg):
  45. idx = i
  46. break
  47. if idx is not None:
  48. opts_args = args[idx:]
  49. args = args[:idx]
  50. all_vals = []
  51. for arg in opts_args:
  52. all_vals.extend(arg.vals)
  53. args.append(CLIArgument(opts_key, *all_vals))
  54. return args