1

The following code in file script.py makes it possible (after chmod 755 script.py) to either script.py dothis or to script.py dothat.

import sys

def dothis():
    print "We're doing this."

def dothat():
    print "We're doing that."

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print "Error: You must specify exactly one function: dothis or dothat"
        sys.exit(1)
    if sys.argv[1] == "dothis":
        dothis()
    elif sys.argv[1] == "dothat":
        dothat()
    else:
        print "I don't know how to "+sys.argv[1]

Is this the most elegant way to call one of two functions from the command line?

Calaf
  • 10,113
  • 15
  • 57
  • 120
  • 1
    Possible duplicate of [Command Line Arguments In Python](http://stackoverflow.com/questions/1009860/command-line-arguments-in-python) – sobolevn Nov 11 '15 at 22:06
  • @sobolevn How about the new variation of the question? Does that make it entirely unique? – Calaf Nov 12 '15 at 01:29

3 Answers3

3
import argparse as ap

def dothis():
    print "We're doing this."

def dothat():
    print "We're doing that."

if __name__ == "__main__":
    parser = ap.ArgumentParser()
    parser.add_argument('thing', choices=['dothis', 'dothat'])
    args = parser.parse_args()
    f = locals()[args.thing]
    f()
wim
  • 338,267
  • 99
  • 616
  • 750
1

There are various options. The argparse module in the standard library is one.

There are also some wrappers that make it easy/easier to use, for example argh. This lets you write:

import argh

# declaring:

def echo(text):
    "Returns given word as is."
    return text

def greet(name, greeting='Hello'):
    "Greets the user with given name. The greeting is customizable."
    return greeting + ', ' + name

# assembling:

parser = argh.ArghParser()
parser.add_commands([echo, greet])

# dispatching:

if __name__ == '__main__':
    parser.dispatch()
circular-ruin
  • 2,834
  • 1
  • 24
  • 30
  • argh looks good, but after `sudo port install py27-argh`, I'm getting "ImportError: No module named argh". – Calaf Nov 12 '15 at 00:54
1

I recommend argparse: https://docs.python.org/2/howto/argparse.html

It supports mutual exclusion of arguments among other features.

davejagoda
  • 2,420
  • 1
  • 20
  • 27