Reputation: 1
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.
Upvotes: 0
Views: 303
Reputation: 2067
It sounds like the sys
module could meet your needs for simple argument parsing.
Example:
myscript.py
import sys
print(sys.argv)
$ python myscript.py ls and other args
['myscript.py', 'ls', 'and', 'other', 'args']
sys.argv
contains all the arguments passed to the python
command. From here, you can use them as you see fit.
Upvotes: 0
Reputation: 2108
What you are looking for is the subprocess module (https://docs.python.org/3/library/subprocess.html). For example if you have to run the bash command "ls -l", you will do the following, as per the documentation.
import subprocess
subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
The documentation also says that " shlex.split() can be useful when determining the correct tokenization for args, especially in complex cases"
import shlex, subprocess
command_line = input()
## /bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
args = shlex.split(command_line)
print(args)
## ['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
p = subprocess.Popen(args) # Success!
I will strongly suggest you to read the documentation, as much as you can, and search for tutorials. Please let me know if this is what you were looking for.
Upvotes: 0