-2

I am writing a python program where in I have included another python file.

The python file included has a method which I want to invoke from the calling script.

Like:

#!/usr/bin/python    
include script1

method = sys.argv[1]     # values may be - create or destroy

if method == "create":
    script1.create()
elif method == "destroy":
    script1.destroy()

Now, what I want is,

#!/usr/bin/python    
include script1

method = sys.argv[1]       # values may be - create or destroy

script1.method()

and, it should use the value inside the variable method instead of trying to call the module called method.

2 Answers2

2

You can use getattr.

method= sys.argv[1]
getattr(script1, method)()
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
0

To call functions from script1, you could turn it into a module.

script1.py:

def create():
   pass

def destroy():
   pass

script2.py:

import script1

script1.create()
script1.destroy()
NPE
  • 486,780
  • 108
  • 951
  • 1,012