简体   繁体   中英

How to take a string and use it as an identifier to call a function?

I have created an autograder for my classes that uses a command line argument to call the associated function for that problem set. I need to extract the command line argument as a string, and then use it as a function call. In the example I'm assigning the string to pset and then calling pset and passing studentFile as the argument. The problem is that the interpreter sees it as a string and not an identifier.

this is a picture of my code

if len(sys.argv) == 2:
    try:
        # find and store the file
        studentFile = helpers.findInSubdirectory(sys.argv[1])
        for i in studentFile.split('/'):
            if i.endswith('.py'):
                pset = i[:-3]
        pset(studentFile)

An unsafe way to do this would be to use eval or look at the globals() dictionary. A slightly safer way would be to create a string-to-function mapping in a dictionary, and look up the function from the mapping.

def foo():
    print('hi')

def bar():
    print('see you')

funs = { 'foo': foo, 'bar': bar }
funs['foo']()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM