0

I've been making heavy use of the answer in "Really Cheap Command-Line Option Parsing in Ruby". It's great and for my purposes, always what I need.

Now I find myself back in Python land for a bit because of internal library support for something I want to do. I'm considering porting it to Ruby but that's beyond the scope of this question, but I'd like to use something similar.

Here is the really cheap method I use often in Ruby:

$quiet       = ARGV.delete('-d')
$interactive = ARGV.delete('-i')

If there is a "-d" in the ARGV array, then $quiet is set to "-d" and not nil. If there is no "-d", then $quiet becomes nil.

Is there something similar I could do in Python?

Community
  • 1
  • 1
Ramy
  • 20,541
  • 41
  • 103
  • 153

5 Answers5

6

You might want to use sys.argv:

from sys import argv
quiet = '-d' in argv # True if '-d' in argv else False

If you want to remove '-d' from the argv, change the second line to this:

quiet = '-d' in argv and (argv.remove('-d') or True)

If this reduces its cheapness, let's make a function of it:

getArg = lambda x: x in argv and (argv.remove(x) or True)
quiet = getArg('-d')
interactive = getArg('-i')
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
rnbguy
  • 1,369
  • 1
  • 10
  • 28
2

Python has a few nice libraries for argument parsing:

  1. argparse
  2. optparse (depreciated since 2.7)

Example:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("-d", action='store_true')
jh314
  • 27,144
  • 16
  • 62
  • 82
1

Try this:

import sys

quiet = 1 if "-d" in sys.argv else None
JoshG79
  • 1,685
  • 11
  • 14
  • This works accurately but mbcoder's response is a bit more thorough and provides a shorter syntax I was looking for. – Ramy Jul 22 '13 at 19:32
1
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-d", action='store_true')

args = parser.parse_args()

if (args.d):
   Print "D switch is on!"
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
Jiminion
  • 5,080
  • 1
  • 31
  • 54
  • don't you need to make a new argparser object first? something like `parser = argparse.ArgumentParser(description='Process some integers.')` from http://docs.python.org/dev/library/argparse.html – Ramy Jul 19 '13 at 20:34
  • Yes. Like jh314 sez. – Jiminion Jul 19 '13 at 20:36
0

IMHO, the lightest way (if you don't want to use argparse) is going to be a helper function:

import sys

def flag(arg):
    try:
        index = sys.argv.index(arg)
    except ValueError:
        return None
    else:
        return sys.argv.pop(index)

Usage:

quiet, interactive = flag("-d"), flag("-i")

Of course, since these are just flags, you could return True and False instead of None and the arg, but I've tried to keep it as similar to the Ruby functionality as posisble.

kindall
  • 178,883
  • 35
  • 278
  • 309