argparse_util.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. #!/usr/bin/env python3
  2. # Copyright (c) Facebook, Inc. and its affiliates.
  3. # All rights reserved.
  4. #
  5. # This source code is licensed under the BSD-style license found in the
  6. # LICENSE file in the root directory of this source tree.
  7. import os
  8. from argparse import Action
  9. class env(Action):
  10. """
  11. Gets argument values from ``PET_{dest}`` before defaulting
  12. to the given ``default`` value. For flags (e.g. ``--standalone``)
  13. use ``check_env`` instead.
  14. .. note:: when multiple option strings are specified, ``dest`` is
  15. the longest option string (e.g. for ``"-f", "--foo"``
  16. the env var to set is ``PET_FOO`` not ``PET_F``)
  17. Example:
  18. ::
  19. parser.add_argument("-f", "--foo", action=env, default="bar")
  20. ./program -> args.foo="bar"
  21. ./program -f baz -> args.foo="baz"
  22. ./program --foo baz -> args.foo="baz"
  23. PET_FOO="env_bar" ./program -f baz -> args.foo="baz"
  24. PET_FOO="env_bar" ./program --foo baz -> args.foo="baz"
  25. PET_FOO="env_bar" ./program -> args.foo="env_bar"
  26. parser.add_argument("-f", "--foo", action=env, required=True)
  27. ./program -> fails
  28. ./program -f baz -> args.foo="baz"
  29. PET_FOO="env_bar" ./program -> args.foo="env_bar"
  30. PET_FOO="env_bar" ./program -f baz -> args.foo="baz"
  31. """
  32. def __init__(self, dest, default=None, required=False, **kwargs) -> None:
  33. env_name = f"PET_{dest.upper()}"
  34. default = os.environ.get(env_name, default)
  35. # ``required`` means that it NEEDS to be present in the command-line args
  36. # rather than "this option requires a value (either set explicitly or default"
  37. # so if we found default then we don't "require" it to be in the command-line
  38. # so set it to False
  39. if default:
  40. required = False
  41. super().__init__(dest=dest, default=default, required=required, **kwargs)
  42. def __call__(self, parser, namespace, values, option_string=None):
  43. setattr(namespace, self.dest, values)
  44. class check_env(Action):
  45. """
  46. For flags, checks whether the env var ``PET_{dest}`` exists
  47. before defaulting to the given ``default`` value. Equivalent to
  48. ``store_true`` argparse built-in action except that the argument can
  49. be omitted from the commandline if the env var is present and has a
  50. non-zero value.
  51. .. note:: it is redundant to pass ``default=True`` for arguments
  52. that use this action because a flag should be ``True``
  53. when present and ``False`` otherwise.
  54. Example:
  55. ::
  56. parser.add_argument("--verbose", action=check_env)
  57. ./program -> args.verbose=False
  58. ./program --verbose -> args.verbose=True
  59. PET_VERBOSE=1 ./program -> args.verbose=True
  60. PET_VERBOSE=0 ./program -> args.verbose=False
  61. PET_VERBOSE=0 ./program --verbose -> args.verbose=True
  62. Anti-pattern (don't do this):
  63. ::
  64. parser.add_argument("--verbose", action=check_env, default=True)
  65. ./program -> args.verbose=True
  66. ./program --verbose -> args.verbose=True
  67. PET_VERBOSE=1 ./program -> args.verbose=True
  68. PET_VERBOSE=0 ./program -> args.verbose=False
  69. """
  70. def __init__(self, dest, default=False, **kwargs) -> None:
  71. env_name = f"PET_{dest.upper()}"
  72. default = bool(int(os.environ.get(env_name, "1" if default else "0")))
  73. super().__init__(dest=dest, const=True, default=default, nargs=0, **kwargs)
  74. def __call__(self, parser, namespace, values, option_string=None):
  75. setattr(namespace, self.dest, self.const)