[报错解决]pip安装torch后import torch报错from torch._C import * ImportError: dlopen...Reason: image not found

Mac
python3.7
pip3 install torch

1、import torch后的报错信息:

Traceback (most recent call last):
  File "", line 1, in 
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/torch/__init__.py", line 136, in 
    from torch._C import *
ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/torch/_C.cpython-37m-darwin.so, 2): Library not loaded: @rpath/libc++.1.dylib
  Referenced from: /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/torch/_C.cpython-37m-darwin.so
Reason: image not found

2、解决方案来源:

https://github.com/cvxgrp/cvxpy/issues/807
[报错解决]pip安装torch后import torch报错from torch._C import * ImportError: dlopen...Reason: image not found_第1张图片

3、具体解决方案

终端输入命令

otool -L /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/torch/_C.cpython-37m-darwin.so

回车后显示

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/torch/_C.cpython-37m-darwin.so:
	@rpath/libshm.dylib (compatibility version 0.0.0, current version 0.0.0)
	@rpath/libtorch_python.dylib (compatibility version 0.0.0, current version 0.0.0)
	@rpath/libc++.1.dylib (compatibility version 1.0.0, current version 1.0.0)
	/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1252.0.0)

zhangmantingdeMacBook-Pro:~ zmt$ install_name_tool -change @rpath/libc++.1.dylib /usr/lib/libc++.1.dylib /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/torch/_C.cpython-37m-darwin.so

再在终端输入命令

install_name_tool -change @rpath/libc++.1.dylib /usr/lib/libc++.1.dylib /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/torch/_C.cpython-37m-darwin.so

回车后没有显示

此时进入python环境下导入包,均未报错

import torch
import torchvision

4、注意

如果你采用了以上办法解决了问题,则不需要看这一点;如果仍未解决,可以看这一点以作参考。

我在使用上文办法前还做了很多在网上搜索到的执行方案。

比如依据这张图
[报错解决]pip安装torch后import torch报错from torch._C import * ImportError: dlopen...Reason: image not found_第2张图片
在终端输入如下命令

sudo install_name_tool -add_rpath /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/torch/_C.so

回车后显示

Usage: /Library/Developer/CommandLineTools/usr/bin/install_name_tool [-change old new] ... [-rpath old new] ... [-add_rpath new] ... [-delete_rpath old] ... [-id name] input

此时再次,import torch依然报同样错

你可能感兴趣的:(Python,python,mac,os,x)