Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save famzah/d09985acbd4c05a44b589d9ea0e74ebd to your computer and use it in GitHub Desktop.
Save famzah/d09985acbd4c05a44b589d9ea0e74ebd to your computer and use it in GitHub Desktop.
$ 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