Skip to content Skip to sidebar Skip to footer

Python Argparse Adds Extra Space Before An Argument

I found that argparse adds an extra space before an argument. Based on the example code below def parse_arguments(): parser = argparse.ArgumentParser( prog='sample', de

Solution 1:

If you directly execute test.py, the extra space won't occur. That happens in the interactive shell because of what you're setting sys.argv to before executing test.py.

sys.argv = ['', '-s /Users/user/Desktop/test']

But when running the script from the terminal and checking sys.argv, you get:

['test.py', '-s', '/Users/user/Desktop/test']

It also ignores multiple spaces between -s and the value when running from terminal.

The shell/terminal already provides each parameter separately to the script (and Python puts them into a list). So the 2nd param is only -s and not -s /Users/user/Desktop/test. Doing sys.argv = ['', '-s', '/Users/user/Desktop/test'] in the interactive shell gives the right result.

What argparse probably does is scan each arg in sys.argv and look for all argument name patterns, -s or --search. Once found, everything after that is the argument value. The = in -s=/Users/user/Desktop/test is standard arg=value notation (more so in the past), so it interprets that as the delimiter between an argument and its value.

Post a Comment for "Python Argparse Adds Extra Space Before An Argument"