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.
If you directly execute
test.py
, the extra space won't occur. That happens in the interactive shell because of what you're settingsys.argv
to before executingtest.py
.But when running the script from the terminal and checking
sys.argv
, you get: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
. Doingsys.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 standardarg=value
notation (more so in the past), so it interprets that as the delimiter between an argument and its value.