Reputation: 804
I met a strange behaviour with my python code today. I wrote the following small program to illustrate.
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--list1", "-l1", nargs='+', help="liste 1", metavar="THE_LIST")
args = parser.parse_args()
if args.list1:
print("list1:" + str(args.list1))
I ran the code on a first server. I got the expected behaviour (list1 contains a string that includes '-V').
$ uname -a
Linux computer 3.2.0-23-generic #36-Ubuntu SMP Tue Apr 10 20:39:51 UTC 2012 x86_64 x86_64 x86_64 GNU/Linux
$ python --version
Python 2.7.3
$ cat test.py
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--list1", "-l1", help="liste 1", metavar="THE_LIST")
args = parser.parse_args()
if args.list1:
print("list1:" + str(args.list1))
$ python test.py -l1 "abc -V def"
list1:abc -V def
I ran it on a second server (Centos 6.6) and got an error. The hyphen seems to be considered as part of an additional argument although the value for -l1 is still enclosed with double quotes... Any idea would be really appreciated...
$ uname -a
Linux sacapus 2.6.32-504.12.2.el6.x86_64 #1 SMP Wed Mar 11 22:03:14 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux
$ python --version
Python 2.7.9
$ cat test.py
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--list1", "-l1", help="liste 1", metavar="THE_LIST")
args = parser.parse_args()
if args.list1:
print("list1:" + str(args.list1))
$ python test.py -l1 "abc -V def"
usage: test.py [-h] [--list1 THE_LIST]
test.py: error: unrecognized arguments: -V def
Upvotes: 3
Views: 1548
Reputation: 7227
This really shouldn't happen. To figure out what's going on, I would include
print(repr(sys.argv))
at the beginning of the script, to isolate if the "abc -V def"
string is really passed as a single argument by the shell.
If it arrives in your program as a single argument blame argparse
, otherwise your shell is messing up. Either way, this seems like something that should become an entry in CentOS's bug database.
FWIW, I can't reproduce this on Debian Jessie with Python 2.7.9:
greek0@orest:/tmp$ python2.7 a.py -l1 "abc -V def"
list1:['abc -V def']
Upvotes: 1