Python 3.12中input()捕获的字符串无法传入dir()的问题
问题解决思路与修正代码
你的核心问题是把模块名字符串当成了模块对象来操作,dir(check_name)实际是对字符串类型调用dir(),自然返回的是字符串的属性方法,不是目标模块的内容。下面是具体修正方案:
关键修正点
- 从
sys.modules中获取实际的模块对象:sys.modules字典的键是模块名字符串,值是对应的模块对象,确认模块已导入后,直接通过键取值就能拿到模块对象。 - 用模块对象调用
dir()、访问__doc__,而不是用字符串。 - 获取模块内的函数时,用
getattr()函数从模块对象中取出函数,而不是字符串拼接。
修正后的完整代码
import sys, os def is_imported(): check_name = input("enter module name: ") # 先判断模块是否已导入,同时获取模块对象 if check_name in sys.modules: module_obj = sys.modules[check_name] print(f"Module name entered is already imported: True") else: print(f"Module name entered is not imported: False") return # 未导入的话直接返回,不执行后续操作 check_functions_in_imported_module = input("\ndo you want to check all functions available in this imported module, press y/n : ") if check_functions_in_imported_module == "y": # 对模块对象调用dir() module_attrs = dir(module_obj) for attr in module_attrs: print(attr) check_wish_to_read_doc_for_module = input("\ndo you want to read doc related to imported module, press y/n : ") if check_wish_to_read_doc_for_module == "y": print(module_obj.__doc__ if module_obj.__doc__ else "该模块无文档字符串") check_wish_to_read_doc_for_fucntions = input("\ndo you want to check a specific function details in this imported module, mention function name : ") if check_wish_to_read_doc_for_fucntions: try: # 用getattr从模块对象中获取函数 func_obj = getattr(module_obj, check_wish_to_read_doc_for_fucntions) print(f"\n函数 {check_wish_to_read_doc_for_fucntions} 的属性列表:") for attr in dir(func_obj): print(attr) print(f"\n函数 {check_wish_to_read_doc_for_fucntions} 的文档字符串:") print(func_obj.__doc__ if func_obj.__doc__ else "该函数无文档字符串") except AttributeError: print(f"模块 {check_name} 中不存在函数 {check_wish_to_read_doc_for_fucntions}") is_imported() while True: check_wish = input("\n\ndo you want to continue checking other imported modules, press y/n ?: ") if check_wish == "y": is_imported() else: print("\nhappy to help when you come back again") break
额外说明
- 若需要支持检查未导入但存在的模块,可以添加自动导入逻辑(比如用
__import__函数),代码中已给出注释示例。 - 新增异常处理逻辑,避免用户输入不存在的函数时程序崩溃。
- 优化了输出格式,让内容更易读。
内容的提问来源于stack exchange,提问作者testcode12092190
相关产品推荐
相关产品推荐

