Search code examples
pythonpython-3.xargparse

Ignoring a substring/linebreak character in CLI arguments using argparse


I'm using the argparse module in Python for the first time, and I haven't touched the language in over a year. I need to solve a bug in a todo list where, if a new task is inputted with a line break, it creates two entries instead of one, e.g.:

$ python todo.py add "Hello,
World!"

will create entries:

0 Hello,
1 World!

Is there a way I can tell argparse to ignore the line break? I have tried looking into the documentation, but couldn't find it.


Solution

  • Remove every newline from the arguments then pass them to parse_args or parse_known_args:

    ArgumentParser.parse_args([arg.replace("\n", "") for arg in sys.argv[1:]])
    

    As ArgumentParser uses sys.argv by default (https://github.com/python/cpython/blob/0924b95f6e678beaf4a059d679515956bac608fb/Lib/argparse.py#L1870), you could also modify sys.argv before the parsing, in the same way:

    sys.argv = sys.argv[0] + [arg.replace("\n", "") for arg in sys.argv[1:]]
    ArgumentParser.parse_args()
    

    Or, still, you could override parse_known_args, as that is where the parsing is done.