Python跨文件调用函数触发全量执行及按键调用函数问题
Python代码问题解答
1. 导入模块时全部代码自动运行的原因
Python导入任意模块时,会默认执行模块内所有顶层代码(即没有封装在函数、类内部的代码)。你当前的代码中,print_menu(menu_options)调用、while True交互循环、退出判断逻辑都属于顶层代码,没有做导入防护,所以被其他文件导入时会全部自动执行。
解决方法:把仅需要直接运行该文件时才执行的代码,放入if __name__ == "__main__":代码块中即可。该判断仅在你直接运行当前py文件时成立,作为模块被导入时判断不成立,内部代码不会执行。
2. 按下对应字母调用目标函数的实现
你现有代码已经完成了输入转大写、分支判断的基础框架,只需要做2处调整即可:
- 修正原代码的缩进错误
- 在对应字母的判断分支中,替换示例print语句,调用你需要执行的目标函数
修正后的完整可运行代码如下:
from T123_P2_func import add_books, books_to_list def print_menu()-> None: menu_options = { 1: 'Command Line L)oad file', 2: 'Command Line A)dd book', 3: 'Command Line R)emove book', 4: 'Command Line F)ind book by title', 5: 'Command Line NC) Number of books in a category', 6: 'Command Line CA) Categories for an author', 7: 'Command Line CB) Categories for a book title', 8:'Command Line G)et book\nR)ate A)uthor P)ublisher C)ategory', } for key in menu_options.keys(): print(key, '-', menu_options[key] ) if __name__ == "__main__": print_menu() file = None while True: userinput = input('Please enter a Command: ').upper() if userinput == 'L': print('Book has been Loaded.') # 调用加载文件函数 file = books_to_list('') elif userinput == 'A': print('Book has been Added.') # 调用添加书籍函数,示例:add_books(参数) elif userinput == 'R': print('Book has been Removed.') # 调用删除书籍函数 elif userinput == 'F': print('Book has been Found.') # 调用查询书籍函数 elif userinput == 'Q': print('程序退出') break print(f"您输入的指令是:{userinput}")
内容的提问来源于stack exchange,提问作者Juststarted1
相关产品推荐
相关产品推荐

