Individual syntax markup in Python

I am writing a shell for my project, which by design analyzes the commands that look like this:

COMMAND_NAME ARG1 = "Long Value" ARG2 = 123 ARG3=me@me.com

My problem is that the Python command line parsing libraries (getopt and optparse) force me to use the "-" or "-" before the arguments. This behavior does not meet my requirements.

Any ideas how this can be solved? Any existing library for this?

+7
python command-line shell parsing arguments
source share
7 answers

You can split them into shlex.split (), which can handle the values ​​you specify, and it's pretty easy to parse this with a simple simple regular expression. Or you can just use regular expressions to separate and parse. Or just use split ().

args = {} for arg in shlex.split(cmdln_args): key, value = arg.split('=', 1) args[key] = value 
+10
source share
  • Try Following 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 the command line arguments are not specified in sys.argv or in a similar list, but on the line, then (as expected, for example, iron- shlex.split() ) use shlex.split() .

 parser.parse_args(["--"+p if "=" in p else p for p in shlex.split(argsline)]) 
+9
source share

A small pythonic variation on the Ironforggy shlex responds:

 args = dict( arg.split('=', 1) for arg in shlex.split(cmdln_args) ) 

oops ... - adjusted.

Thank you, Yu.F. Sebastian (you need to remember these single expressions of the argument generator).

+2
source share

What about optmatch ( http://www.coderazzi.net/python/optmatch/index.htm )? It is not standard, but uses a different approach to parsing parameters and supports any prefix:

OptionMatcher.setMode (optionPrefix = '-')

+1
source share

Without a pretty intense operation on optparse or getopt, I don't believe that you can reasonably get them to parse your format. You can easily parse your own format, or translate it into something that optparse can handle:

 parser = optparse.OptionParser() parser.add_option("--ARG1", dest="arg1", help="....") parser.add_option(...) ... newargs = sys.argv[:1] for idx, arg in enumerate(sys.argv[1:]) parts = arg.split('=', 1) if len(parts) < 2: # End of options, don't translate the rest. newargs.extend(sys.argv[idx+1:]) break argname, argvalue = parts newargs.extend(["--%s" % argname, argvalue]) parser.parse_args(newargs) 
0
source share

A bit late to the party ... but PEP 389 allows this and more.

Here's a bit of a good library if your version of Python needs this code.google.com/p/argparse

Enjoy.

0
source share

You may be interested in the small Python module that I wrote to simplify the processing of command line arguments (open source and free to use) - http://freshmeat.net/projects/commando

0
source share

All Articles