我為我的課程創(chuàng)建了一個自動評分器,它使用命令行參數(shù)來調用該問題集的關聯(lián)函數(shù)。我需要將命令行參數(shù)提取為字符串,然后將其用作函數(shù)調用。在示例中,我將字符串分配給 pset,然后調用 pset 并將 StudentFile 作為參數(shù)傳遞。問題在于解釋器將其視為字符串而不是標識符。這是我的代碼的圖片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)
1 回答

富國滬深
TA貢獻1790條經驗 獲得超9個贊
一種不安全的方法是使用eval或查看globals()字典。稍微安全一點的方法是在字典中創(chuàng)建字符串到函數(shù)的映射,然后從映射中查找函數(shù)。
def foo():
print('hi')
def bar():
print('see you')
funs = { 'foo': foo, 'bar': bar }
funs['foo']()
添加回答
舉報
0/150
提交
取消