OptionParser - support for any option at the end of the command line

I am writing a small program that should execute a command on a remote server (suppose this is a pretty dumb shell 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. The problem is that sometimes a command has an argument that 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 that as soon as I came across the first argument without an option, everything after that should be part of my team.

This, however, gives me:

Usage: floep [options]

floep: error: no such option: -a

OptionParser ? : ? : ?

+5
4

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)

:

$ ./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']
+13

OptionParser . , , , , , ( , , ?). . : .

:

disable_interspersed_args()

-. , , , . , .

+1
from optparse import OptionParser
import subprocess
import os
import sys

parser = OptionParser()
parser.add_option("-q", "--quiet",
                  action="store_true", dest="quiet", default=False,
                  help="don't print output")
parser.add_option("-s", "--signal",
                  action="store_true", dest="signal", default=False,
                  help="signal end of program and return code")

parser.disable_interspersed_args()
(options, command) = parser.parse_args()

if not command:
    parser.print_help()
    sys.exit(1)

if options.quiet:
    ret = subprocess.call(command, stdout=open(os.devnull, 'w'), 
                             stderr=subprocess.STDOUT)
else:
    ret = subprocess.call(command)

if options.signal:
    print "END OF PROGRAM!!! Code: %d" % ret
+1

bash script :

#!/bin/bash
while [ "-" == "${1:0:1}" ] ; do
  if [ "-v" == "${1}" ] ; then
    # do something
    echo "-v"
  elif [ "-s" == "${1}" ] ; then
    # do something
    echo "-s"
  fi
  shift
done
${@}

$ {@} gives you the rest of the command line that was not consumed by switch calls. To use ssh, you simply change the line from $ {@} to ssh $ {user} @ $ {host} $ {@}

test.sh echo bla
bla

test.sh -v echo bla
-v
bla

test.sh -v -s echo bla
-v
-s
bla

-2
source

All Articles