0

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

And also, like you said in an earlier edit, the functions need to be defined before they're looked up in globals. So in addition to removing the parentheses, @SiddTheKid should move all three function declarations above the argument parsing block.
Adding that back. :) Thanks @galenlong.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.