I'm writing a shell for a project of mine, which by design parses commands that looks like this:
COMMAND_NAME ARG1="Long Value" ARG2=123 [email protected]
My problem is that Python's command line parsing libraries (getopt and optparse) forces me to use '-' or '--' in front of the arguments. This behavior doesn't match my requirements.
Any ideas how can this be solved? Any existing library for this?
Argument Parsing using sys.Your program will accept an arbitrary number of arguments passed from the command-line (or terminal) while getting executed. The program will print out the arguments that were passed and the total number of arguments.
The store_true option automatically creates a default value of False. Likewise, store_false will default to True when the command-line argument is not present. The source for this behavior is succinct and clear: http://hg.python.org/cpython/file/2.7/Lib/argparse.py#l861.
You could split them up with shlex.split(), which can handle the quoted values you have, and pretty easily parse this with a very simple regular expression. Or, you can just use regular expressions for both splitting and parsing. Or simply use split().
args = {}
for arg in shlex.split(cmdln_args):
key, value = arg.split('=', 1)
args[key] = value
Try to follow "Standards for Command Line Interfaces"
Convert your arguments (as Thomas suggested) to OptionParser format.
parser.parse_args(["--"+p if "=" in p else p for p in sys.argv[1:]])
If command-line arguments are not in sys.argv or a similar list but in a string then (as ironfroggy suggested) use shlex.split()
.
parser.parse_args(["--"+p if "=" in p else p for p in shlex.split(argsline)])
A small pythonic variation on Ironforggy's shlex answer:
args = dict( arg.split('=', 1) for arg in shlex.split(cmdln_args) )
oops... - corrected.
thanks, J.F. Sebastian (got to remember those single argument generator expressions).
What about optmatch (http://www.coderazzi.net/python/optmatch/index.htm)? Is not standard, but takes a different approach to options parsing, and it supports any prefix:
OptionMatcher.setMode(optionPrefix='-')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With