1

I have the following parser:

def parse(argv: list, actions: list) -> list:
    p = argparse.ArgumentParser()
    p.add_argument('action', type=str, choices=actions)
    p.add_argument('args', nargs='*')

    try:
        return p.parse_args(argv)
    except SystemExit:
        return None

If I type in an invalid option, I get:

usage: main.py [-h] {update,help} [args [args ...]]
main.py: error: argument action: invalid choice: 'test' (choose from 'update', 'help')

in stdout. I don't want to get ANY responses out. Is there a way to mute error responses? I just want to get None if user types invalid argument.

Kousha
  • 32,871
  • 51
  • 172
  • 296
  • FYI running your script on Windows with Python 3.4.3 I don't get any output. Maybe helps somehow – wanaryytel Jan 25 '17 at 02:07
  • @makaveli on Mac and Darwin, I get an output – Kousha Jan 25 '17 at 02:09
  • @makaveli Because this isn't the whole script. Obviously no code executes because there are no statements in the global scope. – Jonathon Reinhart Jan 25 '17 at 02:11
  • 1
    Possible duplicate of [I want Python argparse to throw an exception rather than usage](http://stackoverflow.com/questions/14728376/i-want-python-argparse-to-throw-an-exception-rather-than-usage) – Jonathon Reinhart Jan 25 '17 at 02:11
  • 1
    "I just want to get None if user types invalid argument." Curious: why? That doesn't make much sense towards the user, as they don't know what happened. –  Jan 25 '17 at 02:34
  • @Evert: This is a slack bot. If I get a `None`, I'll then return the `help` description. This is just polluting my log files. I always log inputs and responses, so I already know that the user typed invalid command and that the service responded with the help command – Kousha Jan 25 '17 at 07:14
  • Perhaps I misunderstand, but it sounds like this is not command-line interaction, thus there is no need for argparse: you're already (trying to) handling responses quite differently, and you can probably skip argparse, and use `sys.argv` directly. –  Jan 25 '17 at 10:37
  • @Evert: You are right that it is not CLI, and I do use `sys.argv` but for parsing it, it's more convenient to use this, rather I write my own (specially when it gets to flags) – Kousha Jan 25 '17 at 17:39

0 Answers0