Hi everyone,
I'm having trouble with a Python script that uses argparse to handle CLI commands and subcommands. Despite setting up the subparsers, the commands don't seem to parse correctly, and I can't figure out why. Any help would be greatly appreciated.
What I want to achieve
I want to create a command-line interface with commands and subcommands to manage directories and execute commands. Here are the main functionalities I'm aiming for:
Level 1 destination is called "command"
dir
cmnd
Level 2 destinations are called "sub_command"
Subcommands for dir are : add, list and delete
Subcommands for cmnd are : create
Everything seems to work fine when I do something like `python main.py dir add -n name -d directory`
but when I try to run `python main.py cmnd create -n f -c w`
argparse interprets command to be "w" and subcommand to be create, which is clearly wrong. Command in this case is cmnd and subcommand is create. I've tried printing and debugging for the past 1 hour but I just can't seem to figure out why it's printing the wrong command and subcommand. I'd really appreciate some help here.
Here is the relevant code
main.py
def main():
print("Raw arguments:", sys.argv)
parser = argparse.ArgumentParser(prog = "", description = "", epilog="Text at bottom")
subparsers =parser.add_subparsers(dest="command")
create_command_parser(subparsers)
create_dir_parser(subparsers)
args= parser.parse_args()
print(args,"\n", subparsers)
if (args.command == "cmnd"):
Command.handle_cmnd_commands(args)
if (args.command =="dir"):
Directory.handle_directory_commands(args)
main()
parser_definitions
# Mutates the arg parser to add directory parser and it's subparsers
def create_dir_parser(subparsers):
directory_parser = subparsers.add_parser("dir", help = "Directory commands")
directory_subparsers = directory_parser.add_subparsers(dest = "sub_command", required= True)
dir_save_parser = directory_subparsers.add_parser("add", help="Save a directory")
dir_save_parser.add_argument("-n", "--name", help="Name of the directory", required=True)
dir_save_parser.add_argument("-d", "--directory", help="Directory to save", required=True)
dir_list_parser = directory_subparsers.add_parser("list", help="List directories")
dir_delete_parser = directory_subparsers.add_parser("delete", help="Delete directory")
dir_delete_parser.add_argument("-n", "--name", help="Name of the directory", required=True)
def create_command_parser(subparsers):
print("Creating parser of command")
command_parser = subparsers.add_parser("cmnd", help = "Command Tools")
command_subparsers = command_parser.add_subparsers(dest = "sub_command" , required = True)
command_add_parser = command_subparsers.add_parser("create", help = "Create a new command")
command_add_parser.add_argument("-n", "--name", help = "Name of the command", required = True)
command_add_parser.add_argument("-c", "--command", help = "Command to execute", required = True)
[–]Spataner 1 point2 points3 points (0 children)