[英]Python site-package module not found
我遇到的麻烦主要是因为我对 python 和 OSX 缺乏经验,并试图了解它是如何工作的。
最终目标是让这个模块运行: http://pypi.python.org/pypi/memory_profiler ,除非它永远找不到模块。
所以对于初学者来说,我做了 easy_install 并且一切都安装得很好,据我所知:
easy_install -U memory_profiler # pip install -U memory_profiler
接下来我创建了一个 example.py 文件只是为了让球滚动:
@profile
def my_func():
return 2
if __name__ == '__main__':
my_func()
并尝试运行它,但收到此错误:
$ python example.py
Traceback (most recent call last):
File "example.py", line 2, in <module>
@profile
NameError: name 'profile' is not defined
这不是关于 memory_profiler 模块的问题,而是更多关于我做错了什么和配置不正确的问题? 我使用的是 OSX 10.8.2 和 Python 2.7。
这就是我的“哪个蟒蛇”所说的:
/Library/Frameworks/Python.framework/Versions/Current/bin/python
由于它是一个符号链接,当我转到原始链接时:
/Library/Frameworks/Python.framework/Versions/2.7/bin/python
我感到困惑的是,easy_install 正确地将 memory_profiler.py 文件放在了这个文件夹中:
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages
我知道当 python 运行时,它会检查 PYTHONPATH 和站点包中的模块。 (??)
但是如果模块在 site-packages 文件夹中,为什么 example.py 不起作用? 另外,如果 site-packages 文件夹中的模块应该是路径的一部分,我想我至少可以运行 memory_profiler.py 来看看它是否被 python 运行,但是却得到了这个错误:
python memory_profiler.py
/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python:
can't open file 'memory_profiler.py': [Errno 2] No such file or directory
这也让我感到困惑,因为它说明 python 位于:../2.7/Resources/Python.app/Contents/MacOS/Python,但我认为它应该是 ../2.7/bin/python,并且不应该是否正在检查 ../2.7/lib/python2.7/site-packages 中的 memory_profiler.py 文件?
另外,为什么这两个文件夹都存在,有什么区别?
/System/Library/Frameworks/Python.framework
/Library/Frameworks/Python.framework
我错过了一大块拼图,因此非常感谢您指出正确方向的任何帮助。
更新:
我离开了:
from memory_profiler import profiler
可能是我的大部分笨蛋问题,但现在我收到此错误:
Traceback (most recent call last):
File "example.py", line 1, in <module>
from memory_profiler import profiler
ImportError: cannot import name profiler
我假设你有你的进口报表? from memory_profiler import profiler
... 从阅读您的问题来看,您似乎认为python 会自动从 PYTHONPATH 中的所有模块导入所有内容,这不会因为这会占用太多内存,如果两个模块具有相同的功能会怎样.
编辑
所以看起来@profiler 装饰器工作的唯一方法是从命令行运行程序......
python -m memory_profiler example.py
如果您想在脚本中使用 memory_profiler,请参阅此示例。 https://github.com/fabianp/memory_profiler/blob/master/examples/plot_memory.py
在以前版本的 line_profiler 中,您必须像@johnthexii 指出的那样从命令行运行它。 从命令行运行它仍然是运行分析器的推荐方式(因为它在解释器中设置了一些未设置的钩子),但现在也可以将装饰器导入为
from memory_profiler import profile
我有类似的问题,但结果是我将memory_profiler
安装到 python3 而不是 2。
并指定 python 版本解决了这个问题。
>>> python -m memory_profiler test.py
/usr/bin/python: No module named memory_profiler
>>> python3 -m memory_profiler test.py
Filename: test.py
Line # Mem usage Increment Occurences Line Contents
============================================================
1 19.930 MiB 19.930 MiB 1 @profile
2 def my_func():
3 27.406 MiB 7.477 MiB 1 a = [1] * (10 ** 6)
4 180.031 MiB 152.625 MiB 1 b = [2] * (2 * 10 ** 7)
5 27.586 MiB -152.445 MiB 1 del b
6 27.586 MiB 0.000 MiB 1 return a
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.