Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Customized command line parsing in Python

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?

like image 501
Moshe Avatar asked Oct 01 '08 09:10

Moshe


People also ask

What is command-line parsing in Python?

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.

What is Store_true in Python?

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.


4 Answers

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
like image 52
ironfroggy Avatar answered Sep 28 '22 18:09

ironfroggy


  1. Try to follow "Standards for Command Line Interfaces"

  2. 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)])
like image 22
jfs Avatar answered Sep 28 '22 17:09

jfs


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).

like image 23
gimel Avatar answered Sep 28 '22 16:09

gimel


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='-')

like image 31
Luic Pend Avatar answered Sep 28 '22 16:09

Luic Pend