Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
$ cat a.py
#!/usr/bin/python3
import argparse
p = argparse.ArgumentParser()
p.add_argument('-a', action='store_true')
p.add_argument('-qa', nargs='?')
p.add_argument('-qb', nargs='?')
p.add_argument('command', nargs=argparse.REMAINDER)
print(p.parse_known_args())
$ python3 ./a.py aa -q
usage: a.py [-h] [-a] [-qa [QA]] [-qb [QB]] ...
a.py: error: ambiguous option: -q could match -qa, -qb
@clopez
Copy link

clopez commented Nov 18, 2022

The problem here is caused because argparse tries to recognizes abbreviations before parsing the arguments, so the flag -q confuses it because it is an ambiguous abbreviation (it can mean either -qa or -qb). You can fix this issue by disabling abbreviation:

--- a/a.py
+++ b/a.py
@@ -2,7 +2,7 @@
 
 import argparse
 
-p = argparse.ArgumentParser()
+p = argparse.ArgumentParser(allow_abbrev=False)
 p.add_argument('-a', action='store_true')
 p.add_argument('-qa', nargs='?')
 p.add_argument('-qb', nargs='?')

@famzah
Copy link
Author

famzah commented Nov 18, 2022

Oddly, it still gives the same error.

$ cat a.py

#!/usr/bin/python3

import argparse

p = argparse.ArgumentParser(allow_abbrev=False)
p.add_argument('-a', action='store_true')
p.add_argument('-qa', nargs='?')
p.add_argument('-qb', nargs='?')
p.add_argument('command', nargs=argparse.REMAINDER)
print(p.parse_known_args())

$ ./a.py aa -q

usage: a.py [-h] [-a] [-qa [QA]] [-qb [QB]] ...
a.py: error: ambiguous option: -q could match -qa, -qb

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment