0

I wrote a python program which uses argparse to parse its argument. One of the argument -a is string type and I would like to pass an argument with double dash "--" to it.

import argparse

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description='Trigger `bazel`',
        formatter_class=argparse.RawTextHelpFormatter,
    )
    parser.add_argument(
        '-a',
        dest='a',
        type=str,
        help='Extra arguments for `bazel` command '
             'default to empty',
        required=False,
        default='',
    )
    args = parser.parse_args()
    print(args.a)

E.g. I would like to trigger the command

python3 myprog.py -a --action_env=REPO_ROOT=$PWD

however, it complains error: argument -a: expected one argument I know it is because -- means special in shell that marks end of options. So I also tried

python3 myprog.py -a "--action_env=REPO_ROOT=$PWD"

same error, I am wondering how I can make my python script receive a string to the -a argument "--action_env=REPO_ROOT=/user/pli"

oguz ismail
  • 1
  • 16
  • 47
  • 69
Peiti Li
  • 4,634
  • 9
  • 40
  • 57
  • Add your code to your question (no comment). – Cyrus Feb 06 '21 at 00:37
  • How do you parse arguments in the script ? – jaromir Feb 06 '21 at 00:39
  • 2
    Looks like `argparse` ignores POSIX convention in this case, which means that you basically can't. That's too bad. You could work around it by suggesting a leading space, as in `python3 myprog.py -a " --action_env=REPO_ROOT=$PWD"` – that other guy Feb 06 '21 at 00:50
  • You can use click. It allows for single and double-dash parameters and I think it is much easier to use than argparse. – Eric Truett Feb 06 '21 at 01:01
  • @thatotherguy Thanks, it works, would you elaborate on why a leading space can do the trick? – Peiti Li Feb 06 '21 at 01:02
  • It doesn't do any tricks, it just assumes that an argument with the help text "Extra arguments for 'bazel'` will be processed using something like `args.a.split()`, which causes leading spaces to be ignored. That way, the bug in `argparse` is avoided in a way that the rest of the program doesn't notice. – that other guy Feb 06 '21 at 03:38
  • Does this answer your question? [Can't get argparse to read quoted string with dashes in it?](https://stackoverflow.com/questions/16174992/cant-get-argparse-to-read-quoted-string-with-dashes-in-it) I recommend [this answer](https://stackoverflow.com/a/16175115/4518341), and I just confirmed it works with `-a=--action_env=...` – wjandrea Feb 07 '21 at 20:34

0 Answers0