Python问题:如何在main.py中通过输入调用calls.py指定函数?启动即执行全部函数
问题解决:输入触发函数而非启动时自动执行
问题根源
你在构建commands字典时,直接调用了函数(比如ca.caller1()),这会导致程序一运行到这行代码就立即执行函数,而不是把函数本身存储起来等待后续调用。
修正后的main.py代码
#main.py #import the calls.py file as ca import calls as ca #create dictionary of commands mapping to function objects commands = {} commands['call1'] = ca.caller1 # 去掉括号,存储函数本身 commands['call2'] = ca.caller2 commands['call3'] = ca.caller3 #take input for a command inpt = input('call a function: ') #check if inpt is equal to one of the commands and run the corresponding function if inpt in commands: commands[inpt]() # 这里再调用函数 else: print('unknown command')
关键说明
- 写
ca.caller1()时,Python会立即执行这个函数,并把函数的返回值(此处为None,因为函数无return语句)存入字典。 - 去掉括号后,
ca.caller1是函数对象本身,字典存储的是这个对象,只有执行commands[inpt]()时,才会真正调用对应的函数。
修改后,程序启动时不会执行任何函数,只有输入对应命令(比如call1)后,才会触发相应函数执行。
内容的提问来源于stack exchange,提问作者PrCharles
相关产品推荐
相关产品推荐

