Here is how you can reference the function to call dynamically (from the local symbol table using locals()
)
import sys
def method1(value1, value2):
print(value1)
def method2(value1, value2):
print(value2)
def method_not_found(*args, **kwargs):
print('[-] function not found')
if __name__ == "__main__":
locals().get(sys.argv[3], 'method_not_found')(sys.argv[1], sys.argv[2])
user@pc: python a.py 10 12 method1
10
user@pc: python a.py 10 12 method13
[-] function not found
Explanation:
the way the line:
locals().get(sys.argv[3], 'method_not_found')(sys.argv[1], sys.argv[2])
works is that locals()
return a dict
type and we're calling .get()
method to get refer to the function we're gonna call (if not found, get method_not_found
function instead).
Then after we get the function we want to call, we execute it by passing sys.argv[1], sys.argv[2]
as arguments.