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?
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']
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