Python argparse adds extra space before an argumen

2019-09-06 05:23发布

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',
    description='bla bla',
    parser.add_argument('-s', '--search', dest='pattern', required=True,
    help='search path pattern (e.g. /dir1/dir2/*.ext)')

    args = parser.parse_args()

    if args.pattern[0] == ' ':
        print "One space is added to the argument"
    return args

and testing in interactive shell as:

import sys
sys.argv = ['', '-s /Users/user/Desktop/test']
execfile('test.py')

Providing the argument as sys.argv = ['', '-s=/Users/user/Desktop/test'] does not cause such an addition (inspiring from https://stackoverflow.com/a/36376287/2101864).

Is it a documented behavior or do I miss something? Because it is typical that a regular user provide argument adding a space between argument tag and value.

1条回答
我想做一个坏孩纸
2楼-- · 2019-09-06 06:11

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.

查看更多
登录 后发表回答