-1

I need to run a python program and give it argument that are function names in the code to execute. I can do this by catching the argument by using sys.argv and execute the appropriate functions but I would like to do this automatically since I have a lot functions in my code. For example, when I run

my_program f1 f2 f3

My_program should execute the function named 'f1' and then 'f2', etc. I know this might not sound "pythonic" or even "programmer's way" but I am curious if there is a way.

hsn
  • 114
  • 5
  • 2
    Welcome to Stack Overflow! You seem to be asking for someone to write some code for you. Stack Overflow is a question and answer site, not a code-writing service. Please [see here](http://stackoverflow.com/help/how-to-ask) to learn how to write effective questions. – Morgan Thrapp Nov 03 '15 at 16:28
  • 2
    Yes, there is - read the arguments from `sys.argv[1:]` and use e.g. a dictionary `{'f1': f1, ...}` to select and run the functions based on it. – jonrsharpe Nov 03 '15 at 16:29
  • I think it was already http://stackoverflow.com/questions/7936572/python-call-a-function-from-string-name – Ruslan Galimov Nov 03 '15 at 16:35
  • @jonrsharpe - I think your solution is what OP objects to when he says, "I would like to do this automatically since I have a lot of functions in my code." – Robᵩ Nov 03 '15 at 16:38
  • @Robᵩ well perhaps, but the fact that we have to speculate suggests it's unclear at the moment! – jonrsharpe Nov 03 '15 at 16:42
  • What I am looking was a very simple code (maybe one line) like @Robᵩ's answer. I am not asking anybody to write a full-scale code for me. If I don't have a piece of code in my question, does that mean I am asking somebody to write it for me? – hsn Nov 03 '15 at 17:04

1 Answers1

1

Doing this "automatically" is a bad idea. It opens up your code to all manner of security bugs waiting to happen. Instead, parse the arguments looking specifically for the finite set of function names that you approve of.

But, if you must do it "automatically", you can look up function names in the globals() dict.

import sys

def f1(): print "1"
def f2(): print "2"
def f3(): print "3"

for fname in sys.argv[1:]:
    globals()[fname]()

Edit: Here is a version with a small degree of safety builtin. It will execute f1 or f2, but not f3 nor sys.failsafe_nuclear_launch, for example.

import sys

def f1(): print "1"
f1.safe = True
def f2(): print "2"
f2.safe = True
def f3(): print "3"

for fname in sys.argv[1:]:
    fn = globals()[fname]
    if fn.__dict__.get('safe'):
        fn()
    else:
        print "No %s for you!" % fname
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
  • Thank you @Robᵩ. That's more or less what I want and thank you for the security tip as well. – hsn Nov 03 '15 at 17:05