i have and old script in python, where in
if __name__ == '__main__':
We call arguments of functions. And if it argument equals some string we should call function.
Old code.
if sys.argv[1] == 'add':
sys.exit(add(db, usr))
if sys.argv[1] == 'rem':
sys.exit(rem(db, usr))
if sys.argv[1] == 'rmusr':
sys.exit(rmusr(db, usr))
At the first time, i thought about "switch case", but how i find out, python does not have it. And i tried to loop and array.
Can i use it on this ? Sorry, i started learn python, 2 hours ago. But it is very interesting, and i hope, that you can help me.
actions = ['add','rem','rmusr']
for a in actions:
if sys.argv[1] == 'a':
sys.exit(a(db, usr))
Is it correct ? How i find out, we should not call variables with "$". Please help.
解决方案
You can add the functions to the dictionary and then use the user-input string to retrieve the function:
actions = {
'add': add,
'rem': rem,
'rmusr': rmusr,
}
action = sys.argv[1]
if action in actions:
sys.exit(actions[action](db, usr))