I've read through the Python argparse documentation several times and must be missing something huge. I'm trying to add a makefile like syntax onto my cli tool, but despite the --help flag showing me the expected behavior the execution of it errors out:
test.py
import argparse
import os
def main():
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
make_subparser = subparsers.add_parser("make")
make_subparser.add_argument("update", action="store_false", help="Runs all make targets")
make_subparser.add_argument("clean", action="store_false", help="Cleans up everything done previously")
args = parser.parse_args()
if args.update:
os.system("touch test.txt")
elif args.clean:
os.system("rm test.txt")
else:
print("Bad args, see: python test.py make --help.")
if __name__ == "__main__":
main()
Then in my terminal:
$> python test.py make --help
usage: test.py make [-h]
positional arguments:
update Runs all make targets
$> python test.py make update
usage: test.py [-h] {make} ...
test.py: error: unrecognized arguments: update
$> # this should make a file
$>
$> python test.py make clean
usage: test.py [-h] {make} ...
test.py: error: unrecognized arguments: clean
$> # this should delete the file
This works fine if I swap out the action="store_false" for action="store_true", but there's a dozen make commands so I only want to run the one that the user adds in the cli, if they try to enter any more it should exit.
makebut I am withargparse. Could you expand the example with some more possible arguments to make it clear what you want to achieve? ATM I think you want an argument withoptionsupdatedoesn't mean you are restricted to providing the valueupdateon the command line.python test.py make XI want to run some python code underif args.x == True.store_trueandstore_falseonly make sense withflagged(optionals) arguments. Withstore_false, ` --clean` flag would setargs.cleantoFalse, otherwise it wouldTrue.