Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OptionParser - supporting any option at the end of the command line

I'm writing a small program that's supposed to execute a command on a remote server (let's say a reasonably dumb wrapper around ssh [hostname] [command]).

I want to execute it as such:

./floep [command] 

However, I need to pass certain command lines from time to time:

./floep -v [command]

so I decided to use optparse.OptionParser for this. Problem is, I sometimes the command also has argument, which works fine if I do:

./floep -v "uname -a"

But I also want it to work when I use:

./floep -v uname -a

The idea is, as soon as I come across the first non-option argument, everything after that should be part of my command.

This, however, gives me:

Usage: floep [options]

floep: error: no such option: -a

Does OptionParser support this syntax? If so: how? If not: what's the best way to fix this?

like image 584
Evert Avatar asked Apr 03 '09 22:04

Evert


1 Answers

Try using disable_interspersed_args()

#!/usr/bin/env python
from optparse import OptionParser

parser = OptionParser()
parser.disable_interspersed_args()
parser.add_option("-v", action="store_true", dest="verbose")
(options, args) = parser.parse_args()

print "Options: %s args: %s" % (options, args)

When run:

$ ./options.py foo -v bar
Options: {'verbose': None} args: ['foo', '-v', 'bar']
$ ./options.py -v foo  bar
Options: {'verbose': True} args: ['foo', 'bar']
$ ./options.py foo -a bar
Options: {'verbose': None} args: ['foo', '-a', 'bar']
like image 183
Brian Campbell Avatar answered Oct 05 '22 23:10

Brian Campbell