Commoner
Commoner

Reputation: 1768

Python: Choose function in command line argument

In a Python program (with more than one user defined functions), I want to specify which function to use through command line arguments. For e.g., I have the following functions, func1(), func2(), func3() in my Python program, and I am using the following technique presently:

python prog.py -func func2"

My program is something like this:

from __future__ import division
import numpy as np
import argparse

parser = argparse.ArgumentParser(description='')
parser.add_argument('-func', help='')
args = parser.parse_args()
func_type = globals()[args.func]()

def func1(): 
    print "something1"
def func2(): 
    print "something2"
def func3(): 
    print "something3"

func_type()

I get the following error:

KeyError: 'func2'

I will really appreciate if someone can tell me how I can implement the desired functionality.

Upvotes: 0

Views: 1314

Answers (1)

m0dem
m0dem

Reputation: 1008

Two simple mistakes related to func_type = globals()[args.func]()

  1. The functions you are looking for have not been defined yet. Move the function definitions above this line.

  2. You are calling the function instead of saving a reference to it in variable func_type.

Upvotes: 2

Related Questions