使用Python Profiler时出现ImportError,求问题原因及解决方法
Python cProfile 性能分析命令报错排查
问题
我尝试用Python的cProfile工具做性能分析,执行命令:
python -m cProfile -m HelloWorld.py
出现了如下错误,cProfile文档里没提到"module specification"或"path"相关内容,想问哪里操作有误?
错误信息
Traceback (most recent call last): File "<frozen importlib.util>", line 93, in find_spec AttributeError: module 'HelloWorld' has no attribute '__path__'. Did you mean: '__name__'? The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<frozen runpy>", line 131, in _get_module_details File "<frozen importlib.util>", line 95, in find_spec ModuleNotFoundError: __path__ attribute not found on 'HelloWorld' while trying to find 'HelloWorld.py' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<frozen runpy>", line 198, in _run_module_as_main File "<frozen runpy>", line 88, in _run_code File "C:\Software\Conda\envs\gpd\Lib\cProfile.py", line 197, in <module> main() ~~~~^^ File "C:\Software\Conda\envs\gpd\Lib\cProfile.py", line 186, in main runctx(code, globs, None, options.outfile, options.sort) ~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Software\Conda\envs\gpd\Lib\cProfile.py", line 21, in runctx return _pyprofile._Utils(Profile).runctx(statement, globals, locals, ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ filename, sort) ^^^^^^^^^^^^^^^ File "C:\Software\Conda\envs\gpd\Lib\profile.py", line 64, in runctx prof.runctx(statement, globals, locals) ~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Software\Conda\envs\gpd\Lib\cProfile.py", line 104, in runctx exec(cmd, globals, locals) ~~~~^^^^^^^^^^^^^^^^^^^^^^ File "<string>", line 1, in <module> File "<frozen runpy>", line 222, in run_module File "<frozen runpy>", line 140, in _get_module_details ImportError: Error while finding module specification for 'HelloWorld.py' (ModuleNotFoundError: __path__ attribute not found on 'HelloWorld' while trying to find 'HelloWorld.py'). Try using 'HelloWorld' instead of 'HelloWorld.py' as the module name.
解决方法
问题出在你用-m参数时传了带.py后缀的文件名,-m要求传入模块名(即去掉.py的文件名),有两种正确的命令写法:
- 保持模块运行模式,去掉
.py后缀:
python -m cProfile -m HelloWorld
- 直接运行脚本文件,去掉第二个
-m:
python -m cProfile HelloWorld.py
原因说明
-m参数的作用是让Python将指定模块作为主程序执行,这时候需要传入的是模块名而非带后缀的文件名。你加了.py后,Python会尝试查找名为HelloWorld.py的模块,自然找不到,报错信息最后也明确提示了"Try using 'HelloWorld' instead of 'HelloWorld.py' as the module name"。
内容的提问来源于stack exchange,提问作者Redoute
相关产品推荐
相关产品推荐

