I'm doing a command line app, and want to support user input via commands with arguments. All my google searches point to the argparse library, but that seems to only parse arguments (-h, -m, -i...), not commands (cd, rm...). I'd like something like the Windows command prompt (command ...).
I've tried the argparse library already. I can specify arguments and the parsing works fine.
I've also thought about creating an argument that doesn't require a value and treat it as a command. Example: -c --name 'Bob' --age 37 Argparse says '-c' is an argument, but I would use it as a command. The rest of the arguments would be parsed as regular arguments. But that seems hacky and overly complicated.
Another option would be to parse the first word (the command) by myself and then parse the remaining words (the arguments) using argparse. But again - it feels overly complicated.
I apologize for any any language errors - English is not my first language.
Thanks in advance.
EDIT: Sorry, I didn't clarify when and how the user will input the commands. The user will open the app and type in the commands. Thanks to @CharlesDuffy for pointing that out.
EDIT 2: Subparsers were the answer to my problem. Thanks for that link @GZ0.
How does it work:
I took the user input with input()
, then used the shlex
module (mentioned by @Amit) to split the string into a list. That list was then fed to the parser.parse_args()
method in argparse
.
If anyone is interested in the code here's the link.