0

[linked to] - Store functions in list and call them later

class TestSuites(unittest.TestCase):

def firstHagerTest(self):
    argumentsList = [] 
    for i in sys.argv: 
        argumentsList.append(i) 
    argumentsList.pop(0)
    HagercadLogger.Logger.Log(HagercadLogger.LEVEL_WARNING, "PRINT MY ARGS LIST: " + ', '.join(argumentsList))     
    try:
        func_to_run = globals()[argumentsList] #i have to find a way to make this line work as the line 27 somehow, and of course no matter the no. of elements
        #func_to_run2 = globals()[HagercadUtilities.Utilities.startApp(), HagercadSteps.Steps.createNewProject()] #this work ok 
    except KeyError:
       pass

If i run the script with the hardcoded elements like in func_to_run2 it works as expected. But when I execute it with func_to_run where i pass my list I get the following error:

TypeError: unhashable type: 'list'

argumentsList may contain 5 or 9 elements for example, here it exemplified with 2 so it could be arugmenstList = [startApp(),createProject(),deleteProject(),switchSettings() etc] so no matter how long the list of steps is I want to be able to run them. The arguments are coming from cmd.

What could be the solution for this? Couldn't find anything suitable for me so far.

2 Answers2

1

So I found a solution for this.

    argumentsList = [] 
    for i in sys.argv: 
        argumentsList.append(i)   
    newStrList = [x.encode('UTF8') for x in argumentsList]
    try:
        for indx, val in enumerate(newStrList):
            print(indx, val)
            getattr(ClassContainingMethods,newStrList[indx])()
    except KeyError:
       pass

Now, no matter how many arguments(method calls in this case) are recived in the list they are executed.

0

Look at the following code, I think it can help you:

import importlib

name = 'MyFile.MyClass.startApp'
parts = name.split('.')
module_name, method_name = '.'.join(parts[:-1]), parts[-1]
module = importlib.import_module(module_name)

the you can call getattr(module, method_name)()

Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59
  • I got 'ImportError: No module named Utilities' if i use name = 'HagercadUtilities.Utilities.startApp' wich is correct as path – CristianGrassu Jan 16 '19 at 12:10