0

Example

I have a test.py with this one function

def hello():
    print("hello, world")

Problem

I want to import this module in another module, and then run the script. However, the module will be given as command line argument and thus I have to execute the function only knowing the name of the function as a string. How can I execute it?

What I want to do

python/pseudocode

def main():
    import test
    function_name = "hello"
    run code test["hello"]()

Things I have tried

  • Envoking the function through the modules locals(), but I haven't found a way to make it work.
  • reading the module as string and using exec. However, I don't want to parse the whole module to find its functions etc

Any help is appreciated

Kent Martin
  • 225
  • 2
  • 10
  • 1
    For a *sane* implementation you'd make a map from user input to functions, e.g. `{'hello': hello}[input]()`… – deceze Jun 26 '20 at 11:03
  • Thank you for your input. I still need to be able to execute my function only having the name of the function stored as a string – Kent Martin Jun 26 '20 at 11:05
  • Redefine test.py: ``` def hello(text): print(f"{text}, world") ``` And then use the calling script as follows: ``` def main(): function_name = __import__('test').hello function_name("hello") main() ``` Returning: ``` hello, world ``` – Gustav Rasmussen Jun 26 '20 at 11:11
  • 1
    Have you tried using `eval()`? It would be like `eval("test.hello()")`. – Jortega Jun 26 '20 at 11:13
  • 1
    @Jortega Never use `eval`, especially if it involves *user input*. `getattr(test, function_name)()` works just fine. – deceze Jun 26 '20 at 11:18
  • I doesn't solve my problem since I only have the function name as string. I would need to run `function_name = __import__('test').'hello'` somehow – Kent Martin Jun 26 '20 at 11:19
  • Thanks @Jortega, I will try that. Thanks for the tip! – Kent Martin Jun 26 '20 at 11:20
  • 1
    Read the duplicates and my previous two comments. You have been staring the solution in the face the entire time. Don't use `eval`. – deceze Jun 26 '20 at 11:23
  • @deceze Thanks! getattr() solved my problem beautifully. – Kent Martin Jun 26 '20 at 11:27

0 Answers0