Search code examples
pythonoptparse

How to make a custom command line interface using OptionParser?


I am using the OptionParser from optparse module to parse my command that I get using the raw_input().

I have these questions.

1.) I use OptionParser to parse this input, say for eg. (getting multiple args)

my prompt> -a foo -b bar -c spam eggs 

I did this with setting the action='store_true' in add_option() for '-c',now if there is another option with multiple argument say -d x y z then how to know which arguments come from which option? also if one of the arguments has to be parsed again like

my prompt> -a foo -b bar -c spam '-f anotheroption'

2.) if i wanted to do something like this..

my prompt> -a foo -b bar 
my prompt> -c spam eggs 
my prompt> -d x y z 

now each entry must not affect the other options set by the previous command. how to accomplish these?


Solution

  • For part 2: you want a new OptionParser instance for each line you process. And look at the cmd module for writing a command loop like this.