使用Jython调用Python程序时,由于Python程序使用了numpy库等,而使用java时不会自动导入库,需要手动设置路径。
参考:
https://blog.csdn.net/xfei365/article/details/50996727
https://bbs.csdn.net/topics/392314370?page=1
https://blog.csdn.net/u010882234/article/details/74352492
手动导入报错Jython ImportError: No module named numpy
是因为本地没有相应的库,需要安装,安装numpy需要先安装Python
然而安装了Python之后,安装numpy时报错Python version x.x required, which was not found in the registry
这是注册表里找不到,参考以下网址操作即可:
参考:
https://blog.csdn.net/cakecc2008/article/details/53995665
https://blog.csdn.net/pppii/article/details/48679403
https://blog.csdn.net/u014595019/article/details/48013999
然而装上以后报错
Exception in thread "main" Traceback (most recent call last):
File "D:\rosia\GitLocal\dip\dip-engine\mh.py", line 3, in
import numpy
File "E:\Python27\Lib\site-packages\numpy\__init__.py", line 168, in
from . import add_newdocs
File "E:\Python27\Lib\site-packages\numpy\add_newdocs.py", line 13, in
from numpy.lib import add_newdoc
File "E:\Python27\Lib\site-packages\numpy\lib\__init__.py", line 8, in
from .type_check import *
File "E:\Python27\Lib\site-packages\numpy\lib\type_check.py", line 11, in
import numpy.core.numeric as _nx
File "E:\Python27\Lib\site-packages\numpy\core\__init__.py", line 6, in
from . import multiarray
ImportError: cannot import name multiarray
原因是numpy里面有的文件不是py后缀,是pyd文件,Jython无法导入。
参考:
https://stackoverflow.com/questions/3097466/using-numpy-and-cpython-with-jython
https://stackoverflow.com/questions/316410/is-there-a-good-numpy-clone-for-jython
https://stackoverflow.com/questions/30215271/how-to-setup-numpy-in-jython?lq=1
解决办法是使用java的库代替python的第三方库numpy
选择了jblas
GitHub地址:https://github.com/mikiobraun/jblas
jar包下载:http://jblas.org/download.html
放在本地库中
maven pom依赖:
python文件中import numpy改为from org.jblas import DoubleMatrix
使用到的zeros ones transpose dot方法在DoubleMatrix类中都有,将python脚本中的numpy替换为DoubleMatrix即可
总结:整个过程是一波三折,解决一个问题又来一个问题,这样层层递进。回过头去看,前面几个问题都不用去解决,直接替换成java类库就可以。关于numpy,解决办法不止这一个。有JyNI,还没有实现,jep、jpy找不到怎么操作,java类库除了选用的jblas还有matrix-toolkits-java。很多问题还是要到stackoverflow上找,丰富一点,中文的网上就比较难找到。