java中调用python
在Java中調用Python
</h1><div class="clear"></div><div class="postBody">
寫在前面
在微服務架構大行其道的今天,對于將程序進行嵌套調用的做法其實并不可取,甚至顯得有些愚蠢。當然,之所以要面對這個問題,或許是因為一些歷史原因,或者僅僅是為了簡單。恰好我在項目中就遇到了這個問題,需要在Java程序中調用Python程序。關于在Java中調用Python程序的實現,根據不同的用途可以使用多種不同的方法,在這里就將在Java中調用Python程序的方式做一個總結。
直接通過Runtime進行調用
我們知道,在Java中如果需要調用第三方程序,可以直接通過Runtime實現,這也是最直接最粗暴的做法。
public class InvokeByRuntime {/*** @param args* @throws IOException * @throws InterruptedException */public static void main(String[] args) throws IOException, InterruptedException {String exe = "python";String command = "D:\\calculator_simple.py";String num1 = "1";String num2 = "2";String[] cmdArr = new String[] {exe, command, num1, num2};Process process = Runtime.getRuntime().exec(cmdArr);InputStream is = process.getInputStream();DataInputStream dis = new DataInputStream(is);String str = dis.readLine();process.waitFor();System.out.println(str);}
} 輸出:
3 calculator_simple.py:
# coding=utf-8
from sys import argv
num1 = argv[1]
num2 = argv[2]
sum = int(num1) + int(num2)
print sum
顯然,在Java中通過Runtime調用Python程序與直接執行Python程序的效果是一樣的,可以在Python中讀取傳遞的參數,也可以在Java中讀取到Python的執行結果。需要注意的是,不能在Python中通過return語句返回結果,只能將返回值寫入到標準輸出流中,然后在Java中通過標準輸入流讀取Python的輸出值。
通過Jython調用
通過Jython調用Python?我在聽到這個概念的時候一臉懵逼,不是說好的在Java中調用Python程序嗎?這個Jython是什么鬼?難道是一個在Java中調用Python程序的組件或工具?其實,關于Jython是什么這個疑問,我估計有許多人在一開始接觸的時候也是很疑惑的,下面我們就一一道來。
1. 什么是Jython
Jython主頁:http://www.jython.org/currentdocs.html
按照官方的定義,Jython是Python語言在Java平臺的實現。這個概念似乎有點拗口,反正我一開始并沒有理解。Python難道不已經是一門語言了嗎?什么叫做Jython是Python語言在Java平臺的實現?
實際上,之所以存在這樣的困惑主要是因為我們對Python語言的相關概念掌握和理解不清楚導致的。
Python其實只是一個語言規范,它存在多個不同語言實現的版本。具體來說,目前Python語言存在如下幾個具體實現:
(1)CPython:CPython是標準Python,也是其他Python編譯器的參考實現。通常提到“Python”一詞,都是指CPython。CPython由C編寫,將Python源碼編譯成CPython字節碼,由虛擬機解釋執行。沒有用到JIT等技術,垃圾回收方面采用的是引用計數。
(2)Jython:Jython是在JVM上實現的Python,由Java編寫。Jython將Python源碼編譯成JVM字節碼,由JVM執行對應的字節碼。因此能很好的與JVM集成,比如利用JVM的垃圾回收和JIT,直接導入并調用JVM上其他語言編寫的庫和函數。
(3)IronPython:IronPython與Jython類似,所不同的是IronPython在CLR上實現的Python,即面向.NET平臺,由C#編寫。IronPython將源碼編譯成TODO CLR,同樣能很好的與.NET平臺集成。即與Jython相同,可以利用.NET框架的JIT、垃圾回收等功能,能導入并調用.NET上其他語言編寫的庫和函數。IronPython默認使用Unicode字符串。
(4)PyPy:這里說的PyPy是指使用RPython實現,利用Tracing JIT技術實現的Python,而不是RPython工具鏈。PyPy可以選擇多種垃圾回收方式,如標記清除、標記壓縮、分代等。
(5)Pyston:Pyston由Dropbox開發,使用C++11編寫,采用Method-at-a-time-JIT和Mark Sweep——Stop the World的GC技術。Pyston使用類似JavaScript V8那樣的多層編譯,其中也用到了LLVM來優化代碼。
所以,我們現在再來理解什么是Jython就非常清楚了:Jython是Python語言規范在Java平臺的具體實現。具體來說,可以將Python源碼編譯為JVM可以解釋執行的字節碼。
Jython原本叫做JPython,于1997年由Jim Hugunin創建,后來在1999年2.0版本發布的時候由Barry Warsaw更名為Jython,在這里我們就不再深究為什么要把JPython更名為Jython的原因了。注意: Jython從2.0版本開始就與CPython的版本保持一致,即:Jython 2.7與CPython 2.7保持對應。
雖然我們理解了什么是Jython,但是還存在一個疑問,為什么Python語言存在這么多不同語言的實現呢?為什么不能就只存在一個C語言實現的版本就可以了呢?存在這么多版本,真的給初學者帶來了許多困惑。
當然,要回答這個問題可能就需要深究一些歷史的原因了,就此打住。我們在此只討論使用Jython能做什么以及如何使用Jython?
2. 使用Jython能做什么
既然Jython是Python語言在Java平臺的實現,是Java語言實現的,那么是否可以在Jython程序中調用Java,在Java中也能調用Jython呢?
答案是肯定的,實際上,Jython的主要通途就是在Java中調用Python程序;而且,還可以直接在Jython程序中引用Java。
3. 如何使用Jython
3.1 安裝Jython
在Jython的官方下載頁面我們可以看到如下描述(詳見:http://www.jython.org/downloads.html)
顯然,可以下載2個Jython的jar包。其中,jython-installer-${version}.jar是用于安裝Jython的,jython-standalone-${version}.jar用于嵌入到Java程序中使用。
什么意思?我一開始也是很疑惑,為什么要提供2個不同的jar包呢?他們有什么不同呢?2個不同的Jar包如何使用呢?
首先,jython-installer-${version}.jar用于安裝Jython,就好比我們需要安裝JRE,用于運行Java程序。除此之外,當需要在Python程序中引用一些公共的第三方庫時,也需要先安裝Jython才能下載所依賴的模塊。
下載jython-installer-${version}.jar完畢之后,進入控制臺,執行如下命令:
java -jar jython-installer-${version}.jar
此時會彈出一個圖形化的安裝界面,只需要一步一步選擇相應參數進行安裝即可。安裝完畢之后,請將Jython安裝目錄添加為環境變量JYTHON_HOME,同時添加bin目錄到PATH變量中:PATH=$PATH:$JYTHON_HOME/bin。
進入控制臺,執行如下命令就可以進入Jython的交互環境,這與CPython(我們通常說的Python)的命令行交互環境是一樣的。
> jython
Jython 2.7.0 (default:9987c746f838, Apr 29 2015, 02:25:11)
[Java HotSpot(TM) 64-Bit Server VM (Oracle Corporation)] on java1.8.0_121
Type "help", "copyright", "credits" or "license" for more information.
>>> print("hello,world")
hello,world
>>>
當然,我們還可以使用jython命令運行一個Python程序。
> jython helloworld.py
hello,world
helloworld.py:
import sys
print(“hello,world”)
上面我們看到在Jython官網提供了2個Jar包,一個用于安裝Jython,執行Python程序。那么,jython-standalone-${version}.jar又有什么用途呢?
實際上,當我們需要在Java中調用Python程序時,除了直接使用Java的Runtime調用,還可以直接使用Jython的API進行調用,而且通過Jython API可以直接調用Python程序中的指定函數或者對象方法,粒度更加精細。
當我們需要調用Jython的API時有兩種方式:
第一,如果項目使用Maven進行構建,可以直接添加Jython的依賴配置到pom.xml文件中,如:
<dependency><groupId>org.python</groupId><artifactId>jython</artifactId><version>2.7.0</version>
</dependency>
第二,可以直接將jython-standalone-${version}.jar添加到項目classpath中,這樣也可以調用Jython的相關API了。也就是說,jython-standalone-${version}.jar就是一個提供Jython API的jar獨立jar包。
3.2 Java調用Python程序實踐
Java通過Jython API調用Python程序,有幾種用法:
(1)在Java中執行Python語句,相當于在Java中嵌入了Python程序,這種用法不常見,也沒有太大的實際意義。
public static void main(String[] args) {System.setProperty("python.home", "D:\\jython2.7.0");PythonInterpreter interp = new PythonInterpreter();// 執行Python程序語句interp.exec("import sys");interp.set("a", new PyInteger(42));interp.exec("print a");interp.exec("x = 2+2");PyObject x = interp.get("x");System.out.println("x: " + x);
}
輸出:
42
x: 4
(2)在Java中簡單調用Python程序,不需要傳遞參數,也不需要獲取返回值。
public static void main(String[] args) throws IOException {System.setProperty("python.home", "D:\\jython2.7.0");String python = "D:\\simple_python.py";PythonInterpreter interp = new PythonInterpreter();interp.execfile(python);interp.cleanup();interp.close();
}
simple_python.py:
# coding=utf-8
print("Do simple thing in Python")
print("輸出中文")
(3)在Java中單向調用Python程序中的方法,需要傳遞參數,并接收返回值。Python既支持面向函數式編程,也支持面向對象編程。因此,調用Python程序中的方法也分別以面向函數式編程和面向對象式編程進行說明。
public static void main(String[] args) throws IOException {System.setProperty("python.home", "D:\\jython2.7.0");
<span class="hljs-comment">// 1. Python面向函數式編程: 在Java中調用Python函數</span>
String pythonFunc = <span class="hljs-string">"D:\\calculator_func.py"</span>;PythonInterpreter pi1 = <span class="hljs-keyword">new</span> PythonInterpreter();
<span class="hljs-comment">// 加載python程序</span>
pi1.execfile(pythonFunc);
<span class="hljs-comment">// 調用Python程序中的函數</span>
PyFunction pyf = pi1.get(<span class="hljs-string">"power"</span>, PyFunction.class);
PyObject dddRes = pyf.__call__(Py.newInteger(<span class="hljs-number">2</span>), Py.newInteger(<span class="hljs-number">3</span>));
System.out.println(dddRes);
pi1.cleanup();
pi1.close();<span class="hljs-comment">// 2. 面向對象式編程: 在Java中調用Python對象實例的方法</span>
String pythonClass = <span class="hljs-string">"D:\\calculator_clazz.py"</span>;
<span class="hljs-comment">// python對象名</span>
String pythonObjName = <span class="hljs-string">"cal"</span>;
<span class="hljs-comment">// python類名</span>
String pythonClazzName = <span class="hljs-string">"Calculator"</span>;
PythonInterpreter pi2 = <span class="hljs-keyword">new</span> PythonInterpreter();
<span class="hljs-comment">// 加載python程序</span>
pi2.execfile(pythonClass);
<span class="hljs-comment">// 實例化python對象</span>
pi2.exec(pythonObjName + <span class="hljs-string">"="</span> + pythonClazzName + <span class="hljs-string">"()"</span>);
<span class="hljs-comment">// 獲取實例化的python對象</span>
PyObject pyObj = pi2.get(pythonObjName);
<span class="hljs-comment">// 調用python對象方法,傳遞參數并接收返回值</span>
PyObject result = pyObj.invoke(<span class="hljs-string">"power"</span>, <span class="hljs-keyword">new</span> PyObject[] {Py.newInteger(<span class="hljs-number">2</span>), Py.newInteger(<span class="hljs-number">3</span>)});
<span class="hljs-keyword">double</span> power = Py.py2double(result);
System.out.println(power);pi2.cleanup();
pi2.close();
}
輸出:
8.0
8.0
calculator_func.py:
# coding=utf-8
import math
# 面向函數式編程
def power(x, y):
return math.pow(x, y)
calculator_clazz.py:
# coding=utf-8
import math
# 面向對象編程
class Calculator(object):
<span class="hljs-comment"># 計算x的y次方</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">power</span><span class="hljs-params">(self, x, y)</span>:</span><span class="hljs-keyword">return</span> math.pow(x,y)</code></pre>
(4)高級調用,也是在Java中調用Python程序最常見的用法:Python程序可以實現Java接口,在Python中也可以調用Java方法。
public static void main(String[] args) throws IOException {System.setProperty("python.home", "D:\\jython2.7.0");
<span class="hljs-comment">// Python程序路徑</span>
String python = <span class="hljs-string">"D:\\python\\fruit_controller.py"</span>;
<span class="hljs-comment">// Python實例對象名</span>
String pyObjName = <span class="hljs-string">"pyController"</span>;
<span class="hljs-comment">// Python類名</span>
String pyClazzName = <span class="hljs-string">"FruitController"</span>;Fruit apple = <span class="hljs-keyword">new</span> Apple();
Fruit orange = <span class="hljs-keyword">new</span> Orange();PythonInterpreter interpreter = <span class="hljs-keyword">new</span> PythonInterpreter();
<span class="hljs-comment">// 如果在Python程序中引用了第三方庫,需要將這些被引用的第三方庫所在路徑添加到系統環境變量中</span>
<span class="hljs-comment">// 否則,在執行Python程序時將會報錯: ImportError: No module named xxx</span>
PySystemState sys = interpreter.getSystemState();
sys.path.add(<span class="hljs-string">"D:\\python"</span>);<span class="hljs-comment">// 加載Python程序</span>
interpreter.execfile(python);
<span class="hljs-comment">// 實例 Python對象</span>
interpreter.exec(pyObjName + <span class="hljs-string">"="</span> + pyClazzName + <span class="hljs-string">"()"</span>);<span class="hljs-comment">// 1.在Java中獲取Python對象,并將Python對象轉換為Java對象</span>
<span class="hljs-comment">// 為什么能夠轉換? 因為Python類實現了Java接口,通過轉換后的Java對象只能調用接口中定義的方法</span>
GroovyController controller = (GroovyController) interpreter.get(pyObjName).__tojava__(GroovyController.class);
controller.controllFruit(apple);
controller.controllFruit(orange);<span class="hljs-comment">// 2.在Java直接通過Python對象調用其方法</span>
<span class="hljs-comment">// 既可以調用實現的Java接口方法,也可以調用Python類自定義的方法</span>
PyObject pyObject = interpreter.get(pyObjName);
pyObject.invoke(<span class="hljs-string">"controllFruit"</span>, Py.java2py(apple));
pyObject.invoke(<span class="hljs-string">"controllFruit"</span>, Py.java2py(orange));
pyObject.invoke(<span class="hljs-string">"printFruit"</span>, Py.java2py(apple));
pyObject.invoke(<span class="hljs-string">"printFruit"</span>, Py.java2py(orange));<span class="hljs-comment">// 3.在Java中獲取Python類進行實例化對象: 沒有事先創建 Python對象</span>
PyObject pyClass = interpreter.get(<span class="hljs-string">"FruitController"</span>);
PyObject pyObj = pyClass.__call__();
pyObj.invoke(<span class="hljs-string">"controllFruit"</span>, Py.java2py(apple));
pyObj.invoke(<span class="hljs-string">"controllFruit"</span>, Py.java2py(orange));PyObject power = pyObj.invoke(<span class="hljs-string">"power"</span>, <span class="hljs-keyword">new</span> PyObject[] {Py.newInteger(<span class="hljs-number">2</span>), Py.newInteger(<span class="hljs-number">3</span>)});
<span class="hljs-keyword">if</span>(power != <span class="hljs-keyword">null</span>) {<span class="hljs-keyword">double</span> p = Py.py2double(power);System.out.println(p);
}interpreter.cleanup();
interpreter.close();
}
輸出:
Show: I am a java apple.
controllFruit Python Apple
controllFruit END
Show: I am a java orange.
controllFruit Python Orange
controllFruit END
Show: I am a java apple.
controllFruit Python Apple
controllFruit END
Show: I am a java orange.
controllFruit Python Orange
controllFruit END
Show: I am a java apple.
printFruit Python Apple
printFruit END
Show: I am a java orange.
printFruit Python Orange
printFruit END
Show: I am a java apple.
controllFruit Python Apple
controllFruit END
Show: I am a java orange.
controllFruit Python Orange
controllFruit END
8.0
fruit_controller.py:
# coding=utf-8
from calculator_clazz import Calculator
from java.lang import String
from org.test.inter import GroovyController
from org.test.inter import Fruit
# 在Python中實現Java接口: org.test.inter.GroovyController
class FruitController(GroovyController):
<span class="hljs-comment"># 實現接口方法</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">controllFruit</span><span class="hljs-params">(self, fruit)</span>:</span><span class="hljs-comment"># 在Python中調用Java對象方法</span>fruit.show()<span class="hljs-keyword">if</span>(fruit.getType() == <span class="hljs-string">"apple"</span>):<span class="hljs-keyword">print</span> (<span class="hljs-string">"controllFruit Python Apple"</span>)<span class="hljs-keyword">if</span>(fruit.getType() == <span class="hljs-string">"orange"</span>):<span class="hljs-keyword">print</span> (<span class="hljs-string">"controllFruit Python Orange"</span>)<span class="hljs-keyword">print</span> (<span class="hljs-string">"controllFruit END"</span>)<span class="hljs-comment"># 自定義新方法 </span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">printFruit</span><span class="hljs-params">(self, fruit)</span>:</span>fruit.show()<span class="hljs-keyword">if</span>(fruit.getType() == <span class="hljs-string">"apple"</span>):<span class="hljs-keyword">print</span> (<span class="hljs-string">"printFruit Python Apple"</span>)<span class="hljs-keyword">if</span>(fruit.getType() == <span class="hljs-string">"orange"</span>):<span class="hljs-keyword">print</span> (<span class="hljs-string">"printFruit Python Orange"</span>)<span class="hljs-keyword">print</span> (<span class="hljs-string">"printFruit END"</span>)<span class="hljs-comment"># 引用第三方python程序</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">power</span><span class="hljs-params">(self, x, y)</span>:</span>cal = Calculator()<span class="hljs-keyword">return</span> cal.power(x, y)</code></pre>
Java接口和實現類:
// 該接口用于在Python中實現
public interface GroovyController {public void controllFruit(Fruit fruit);
}
// 在Java中使用的接口
public interface Fruit {
public String getName();
public String getType();
public void show();
}
// Apple
public class Apple implements Fruit {
public String getName() {
return “java apple”;
}
<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getType</span><span class="hljs-params">()</span> </span>{<span class="hljs-keyword">return</span> <span class="hljs-string">"apple"</span>;
}<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">show</span><span class="hljs-params">()</span> </span>{System.out.println(<span class="hljs-string">"Show: I am a java apple."</span>);
}
}
// Orange
public class Orange implements Fruit {
public String getName() {
return “ava orange”;
}
<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getType</span><span class="hljs-params">()</span> </span>{<span class="hljs-keyword">return</span> <span class="hljs-string">"orange"</span>;
}<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">show</span><span class="hljs-params">()</span> </span>{System.out.println(<span class="hljs-string">"Show: I am a java orange."</span>);
}
}
另外,對于在eclipse中運行時控制臺報錯:
Failed to install '': java.nio.charset.UnsupportedCharsetException: cp0
請添加VM參數:-Dpython.console.encoding=UTF-8,詳見:http://blog.csdn.net/xfei365/article/details/50955731
總結
雖然在Java中調用Python可以有多種方式解決,甚至因為Jython的出現更顯得非常便利。但是這種程序間嵌套調用的方式不可取,首先拋開調用性能不說,增加了耦合復雜度。更加有效的方式應該是通過RCP或者RESTful接口進行解耦,這樣各司其職,也便于擴展,良好的架構是一個項目能夠健康發展的基礎。在微服務架構大行其道的今天,這種程序間嵌套調用的方式將會逐漸被淘汰。
【參考】
http://tonl.iteye.com/blog/1918245 Java調用Python
http://blog.csdn.net/supermig/article/details/24005585 Learning Python -- Java 通過JyThon調用Python實現的規則
http://blog.csdn.net/hpp1314520/article/details/72854011 java 利用Runtime.getRuntime().exec()調用python腳本并傳參
http://blog.csdn.net/xingjiarong/article/details/49424253 java調用python方法總結
https://zh.wikipedia.org/wiki/Jython Jython
http://lib.csdn.net/article/python/1654 Jython的安裝及簡單例子
https://coolshell.cn/articles/2631.html 五大基于JVM的腳本語言
http://python.jobbole.com/82703/ 各種 Python 實現的簡單介紹與比較
https://www.oschina.net/translate/why-are-there-so-many-pythons 為什么有這么多 Python?
作者:2Simple
出處:http://www.cnblogs.com/nuccch/
聲明:本文版權歸作者和博客園共有,歡迎轉載,但請在文章頁面明顯位置給出原文連接。
<div id="blog_post_info">
好文要頂 關注我 收藏該文
2Simple關注 - 2
粉絲 - 69 +加關注 4 0
<div class="clear"></div>
<div id="post_next_prev"><a href="https://www.cnblogs.com/nuccch/p/8433442.html" class="p_n_p_prefix">? </a> 上一篇: <a href="https://www.cnblogs.com/nuccch/p/8433442.html" title="發布于 2018-02-08 22:18">UUID在Java中的實現與應用</a>
<br>
<a href="https://www.cnblogs.com/nuccch/p/8436485.html" class="p_n_p_prefix">? </a> 下一篇: <a href="https://www.cnblogs.com/nuccch/p/8436485.html" title="發布于 2018-02-09 18:05">優秀博客推薦</a>
posted @ 2018-02-09 15:33?2Simple 閱讀(60370) 評論(28) 編輯 收藏
評論列表
<div class="feedbackItem"><div class="feedbackListSubtitle"><div class="feedbackManage">
</div><!-- Title -->
#1樓
<!-- PostDate -->
2018-07-06 10:48
<!--NameLink--><a id="a_comment_author_4014016" href="https://home.cnblogs.com/u/1388842/" target="_blank">我需要學習</a><div class="feedbackCon">
大佬這是已經調了第三方依賴嗎
支持(0) 反對(0)
</div></div></div><div class="feedbackItem"><div class="feedbackListSubtitle"><div class="feedbackManage">
</div><!-- Title -->
#2樓
[樓主]
<!-- PostDate -->
2018-07-07 21:27
<!--NameLink--><a id="a_comment_author_4015211" href="https://www.cnblogs.com/nuccch/" target="_blank">2Simple</a><div class="feedbackCon">
@ 我需要學習博客中的示例沒有調用第三方依賴包,在實際項目中已經遇到需要通過Jython調用第三方依賴包的情況了。 支持(0) 反對(0) https://pic.cnblogs.com/face/722072/20190303092130.png
</div></div></div><div class="feedbackItem"><div class="feedbackListSubtitle"><div class="feedbackManage">
</div><!-- Title -->
#3樓
<!-- PostDate -->
2018-07-09 09:20
<!--NameLink--><a id="a_comment_author_4015784" href="https://home.cnblogs.com/u/1388842/" target="_blank">我需要學習</a><div class="feedbackCon">
怎么調用第三方的的依賴包啊 求教 感謝
支持(0) 反對(0)
</div></div></div><div class="feedbackItem"><div class="feedbackListSubtitle"><div class="feedbackManage">
</div><!-- Title -->
#4樓
[樓主]
<!-- PostDate -->
2018-07-10 10:14
<!--NameLink--><a id="a_comment_author_4016778" href="https://www.cnblogs.com/nuccch/" target="_blank">2Simple</a><div class="feedbackCon">
@ 我需要學習是依賴的python庫嗎還是java庫?
如果需要依賴第三方的python庫,那么還是需要安裝python自己的依賴管理進行處理,直接將第三方python庫安裝到$PYTHON_HOME/Lib/site-packages就可以了,簡單點說,你可以直接使用pip進行安裝第三方庫就行。 支持(0) 反對(0) https://pic.cnblogs.com/face/722072/20190303092130.png
</div></div></div><div class="feedbackItem"><div class="feedbackListSubtitle"><div class="feedbackManage">
</div><!-- Title -->
#5樓
<!-- PostDate -->
2018-07-10 14:43
<!--NameLink--><a id="a_comment_author_4017045" href="https://www.cnblogs.com/zpf336/" target="_blank">豐峰鋒</a><div class="feedbackCon">
@ 老C的技術文摘你用的是$PYTHON_HOME/Lib/site-packages,這個是指Python的路徑還是只Jython的路徑?然后如果是Python的路徑,可以順利安裝,可是如果是jython的easy_install 去安裝到jython的路徑,安裝就會報各種依賴找不到。
如何使用呢?如果成功安裝,如何使用呢,經測試,把這個路徑加入到path中,還是報依賴找不到,路徑不正確等:例如:
Exception in thread "main" Traceback (most recent call last):File "<string>", line 1, in <module>File "C:\jython2.7\Lib\site-packages\numpy\__init__.py", line 142, in <module>from . import add_newdocsFile "C:\jython2.7\Lib\site-packages\numpy\add_newdocs.py", line 13, in <module>from numpy.lib import add_newdocFile "C:\jython2.7\Lib\site-packages\numpy\lib\__init__.py", line 8, in <module>from .type_check import *
ImportError: No module named type_check
支持(0) 反對(0)
https://pic.cnblogs.com/face/749431/20150703143415.png
</div></div></div><div class="feedbackItem"><div class="feedbackListSubtitle"><div class="feedbackManage">
</div><!-- Title -->
#6樓
[樓主]
<!-- PostDate -->
2018-07-12 22:29
<!--NameLink--><a id="a_comment_author_4019262" href="https://www.cnblogs.com/nuccch/" target="_blank">2Simple</a><div class="feedbackCon">
@ 豐峰鋒這個$PYTHON_HOME就是安裝Jython的目錄。
另外,注意一點:Python和Jython是2種不同語言實現的Python,只需要安裝其中之一就行了。實際上,我們通常說的Python是C語言實現的Python,嚴格來說應該叫C Python。 支持(0) 反對(0) https://pic.cnblogs.com/face/722072/20190303092130.png
</div></div></div><div class="feedbackItem"><div class="feedbackListSubtitle"><div class="feedbackManage">
</div><!-- Title -->
#7樓
<!-- PostDate -->
2018-09-17 15:27
<!--NameLink--><a id="a_comment_author_4069140" href="https://home.cnblogs.com/u/955142/" target="_blank">廖昫</a><div class="feedbackCon">
兄弟,我也在調用第三方庫是提示ImportError: No module named xxx,我不知道該把這個庫放哪里,我用pip安裝成功了,在spyder都可以調用,但是這邊不行,問題在哪里?謝謝
支持(0) 反對(0)
</div></div></div><div class="feedbackItem"><div class="feedbackListSubtitle"><div class="feedbackManage">
</div><!-- Title -->
#8樓
[樓主]
<!-- PostDate -->
2018-09-18 10:57
<!--NameLink--><a id="a_comment_author_4069838" href="https://www.cnblogs.com/nuccch/" target="_blank">2Simple</a><div class="feedbackCon">
@ 廖昫放在$PYTHON_HOME/Lib/site-packages 支持(0) 反對(0) https://pic.cnblogs.com/face/722072/20190303092130.png
</div></div></div><div class="feedbackItem"><div class="feedbackListSubtitle"><div class="feedbackManage">
</div><!-- Title -->
#9樓
<!-- PostDate -->
2018-09-18 11:02
<!--NameLink--><a id="a_comment_author_4069849" href="https://www.cnblogs.com/lmm361027282/" target="_blank">廖昫</a><div class="feedbackCon">
謝謝,我有在這下面都放著,用pip安裝的,也試了用Anaconda prompt安裝也不行,我還以為是版本問題,安裝了不同版本都不行,不知道哪里出了問題,我在spyder里面都可以正常訪問,在java里面用PythonInterpreter就報錯,夠折騰人啊
支持(0) 反對(0)
</div></div></div><div class="feedbackItem"><div class="feedbackListSubtitle"><div class="feedbackManage">
</div><!-- Title -->
#10樓
<!-- PostDate -->
2018-09-18 11:32
<!--NameLink--><a id="a_comment_author_4069897" href="https://www.cnblogs.com/lmm361027282/" target="_blank">廖昫</a><div class="feedbackCon">
如果在Python程序中引用了第三方庫,需要將這些被引用的第三方庫所在路徑添加到系統環境變量中這句是真的嗎?需要配置在系統環境變量?,謝謝 支持(0) 反對(0)
</div></div></div><div class="feedbackItem"><div class="feedbackListSubtitle"><div class="feedbackManage">
</div><!-- Title -->
#11樓
[樓主]
<!-- PostDate -->
2018-09-18 21:21
<!--NameLink--><a id="a_comment_author_4070535" href="https://www.cnblogs.com/nuccch/" target="_blank">2Simple</a><div class="feedbackCon">
@ 廖昫關于我在代碼中的這句注釋:
“// 如果在Python程序中引用了第三方庫,需要將這些被引用的第三方庫所在路徑添加到系統環境變量中
// 否則,在執行Python程序時將會報錯: ImportError: No module named xxx
”
至少我在實踐的時候發現是這樣的,您不妨實驗一下。 支持(0) 反對(0) https://pic.cnblogs.com/face/722072/20190303092130.png
</div></div></div><div class="feedbackItem"><div class="feedbackListSubtitle"><div class="feedbackManage">
</div><!-- Title -->
#12樓
<!-- PostDate -->
2018-09-19 09:03
<!--NameLink--><a id="a_comment_author_4070726" href="https://www.cnblogs.com/lmm361027282/" target="_blank">廖昫</a><div class="feedbackCon">
非常非常感謝兄弟一直在一起幫我解決這個問題我剛剛配了系統環境變量也不行,
C:\Users\liaomingming\Anaconda3\Lib\site-packages
連C:\Users\liaomingming\Anaconda3\Lib\site-packages\numpy這個都單獨放在系統變量還是不行,請問兄弟你是怎么配的?
非常非常感謝 支持(0) 反對(0)
</div></div></div><div class="feedbackItem"><div class="feedbackListSubtitle"><div class="feedbackManage">
</div><!-- Title -->
#13樓
[樓主]
<!-- PostDate -->
2018-09-19 10:16
<!--NameLink--><a id="a_comment_author_4070821" href="https://www.cnblogs.com/nuccch/" target="_blank">2Simple</a><div class="feedbackCon">
@ 廖昫通過代碼添加的啊,不是直接去配置系統的環境變量
PythonInterpreter interpreter = new PythonInterpreter();
PySystemState sys = interpreter.getSystemState();
sys.path.add("D:\\python"); // 在代碼中添加程序執行的環境變量路徑
支持(0) 反對(0)
https://pic.cnblogs.com/face/722072/20190303092130.png
</div></div></div><div class="feedbackItem"><div class="feedbackListSubtitle"><div class="feedbackManage">
</div><!-- Title -->
#14樓
<!-- PostDate -->
2018-09-19 10:19
<!--NameLink--><a id="a_comment_author_4070825" href="https://www.cnblogs.com/lmm361027282/" target="_blank">廖昫</a><div class="feedbackCon">
是的我也這樣做了,sys.path.add("C:\\Users\\liaomingming\\Anaconda3\\Lib\\site-packages\\numpy");
sys.path.add("C:\\Users\\liaomingming\\Anaconda3\\Lib\\site-packages\\psycopg2");
現在出現新的錯誤
from .porter import PorterStemmer # noqa:F401
SyntaxError: ("'with' will become a reserved keyword in Python 2.6", 支持(0) 反對(0)
</div></div></div><div class="feedbackItem"><div class="feedbackListSubtitle"><div class="feedbackManage">
</div><!-- Title -->
#15樓
[樓主]
<!-- PostDate -->
2018-09-19 10:43
<!--NameLink--><a id="a_comment_author_4070864" href="https://www.cnblogs.com/nuccch/" target="_blank">2Simple</a><div class="feedbackCon">
@ 廖昫顯然,這是新的問題,應該是Python版本的不兼容導致的,這個問題你應該能解決了 支持(0) 反對(0) https://pic.cnblogs.com/face/722072/20190303092130.png
</div></div></div><div class="feedbackItem"><div class="feedbackListSubtitle"><div class="feedbackManage">
</div><!-- Title -->
#16樓
<!-- PostDate -->
2018-09-19 10:52
<!--NameLink--><a id="a_comment_author_4070880" href="https://www.cnblogs.com/lmm361027282/" target="_blank">廖昫</a><div class="feedbackCon">
是的,需要找匹配的版本,真是非要坑死人,非常感謝兄弟兄弟有沒用過python作為服務器語言搭建服務器 支持(0) 反對(0)
</div></div></div><div class="feedbackItem"><div class="feedbackListSubtitle"><div class="feedbackManage">
</div><!-- Title -->
#17樓
<!-- PostDate -->
2018-09-19 11:29
<!--NameLink--><a id="a_comment_author_4070944" href="https://www.cnblogs.com/lmm361027282/" target="_blank">廖昫</a><div class="feedbackCon">
我下載了最新的jython,2.7.0這個版本,現在運行報File "C:\Users\liaomingming\Anaconda3\Lib\site-packages\gensim\utils.py", line 31, in <module>
import multiprocessing
ImportError: No module named multiprocessing
又出現沒有module的錯,我這個小心臟啊,gensim這個庫我才最新安裝的,難道每個庫包都要一一檢查重新再下載!這折騰的要哭瞎 支持(0) 反對(0)
</div></div></div><div class="feedbackItem"><div class="feedbackListSubtitle"><div class="feedbackManage">
</div><!-- Title -->
#18樓
[樓主]
<!-- PostDate -->
2018-09-19 14:14
<!--NameLink--><a id="a_comment_author_4071138" href="https://www.cnblogs.com/nuccch/" target="_blank">2Simple</a><div class="feedbackCon">
@ 廖昫 關于安裝包依賴這個,我之前的解決方案是,先安裝CPython,把對應的依賴包下載下來,再拷貝到JPython對應的位置。直接通過JPython安裝依賴包貌似有時候不成功,不知道原因。 支持(0) 反對(0) https://pic.cnblogs.com/face/722072/20190303092130.png
</div></div></div><div class="feedbackItem"><div class="feedbackListSubtitle"><div class="feedbackManage">
</div><!-- Title -->
#19樓
<!-- PostDate -->
2018-09-19 15:07
<!--NameLink--><a id="a_comment_author_4071227" href="https://www.cnblogs.com/lmm361027282/" target="_blank">廖昫</a><div class="feedbackCon">
謝謝兄弟一直在不斷地指導我,先安裝CPython,把對應的依賴包下載下來,再拷貝到JPython對應的位置。直接通過JPython安裝依賴包貌似有時候不成功
這句我沒怎么看懂,對應的庫是指Cython嗎?現在我引用的是numpy這個庫,好像跟cython沒什么關系吧
資料很不好找,在stackoverflow上面找個兩個例子,但是都是問題,也沒有正確而答案 支持(0) 反對(0)
</div></div></div><div class="feedbackItem"><div class="feedbackListSubtitle"><div class="feedbackManage">
</div><!-- Title -->
#20樓
[樓主]
<!-- PostDate -->
2018-09-19 15:57
<!--NameLink--><a id="a_comment_author_4071367" href="https://www.cnblogs.com/nuccch/" target="_blank">2Simple</a><div class="feedbackCon">
@ 廖昫Python語言存在多個版本這個你知道吧?
我們通常所說的Python就是CPython,我這篇博客里面用的是JPython,是Java語言實現的Python。
所以我理解你的場景是在Java中調用Python程序,使用的是JPython(我寫的這篇博客主要講的也是如何在Java中使用JPython)。
也就是說,如果你的場景跟我的一樣,我理解你在開發機器上裝的是JPython,而不是CPython。我之前的經歷是安裝JPython之后安裝依賴包存在不成功的現象,然后我就安裝CPython,通過CPython去下載依賴包,然后再拷貝到JPthon安裝的對應位置就解決了。 支持(0) 反對(0) https://pic.cnblogs.com/face/722072/20190303092130.png
</div></div></div><div class="feedbackItem"><div class="feedbackListSubtitle"><div class="feedbackManage">
</div><!-- Title -->
#21樓
<!-- PostDate -->
2018-09-19 17:33
<!--NameLink--><a id="a_comment_author_4071548" href="https://www.cnblogs.com/lmm361027282/" target="_blank">廖昫</a><div class="feedbackCon">
然后我就安裝CPython,通過CPython去下載依賴包,然后再拷貝到JPthon安裝的對應位置就解決了我安裝Cython都報錯
我是用pip install Cython安裝的,你是怎么安裝的? 支持(0) 反對(0)
</div></div></div><div class="feedbackItem"><div class="feedbackListSubtitle"><div class="feedbackManage">
</div><!-- Title -->
#22樓
[樓主]
<!-- PostDate -->
2018-09-19 22:44
<!--NameLink--><a id="a_comment_author_4071838" href="https://www.cnblogs.com/nuccch/" target="_blank">2Simple</a><div class="feedbackCon">
@ 廖昫我感覺你沒理解Python存在多個語言版本的含義
CPython安裝包下載地址了解一下:https://www.python.org/downloads/windows/
windows下exe文件一步步就安裝好了 支持(0) 反對(0) https://pic.cnblogs.com/face/722072/20190303092130.png
</div></div></div><div class="feedbackItem"><div class="feedbackListSubtitle"><div class="feedbackManage">
</div><!-- Title -->
#23樓
<!-- PostDate -->
2018-09-20 09:18
<!--NameLink--><a id="a_comment_author_4071983" href="https://www.cnblogs.com/lmm361027282/" target="_blank">廖昫</a><div class="feedbackCon">
是,我有些模糊,我之前安裝的是cython嗎?就是純python環境下的,做算法那些。jython我下過一個安裝版,也安裝了,也下了一個直接嵌入工程的jar包
你的意思是要我下載一個cython,然后把包拷到jython是嗎?因為java運行調用python應該是調用jython,如果這樣把cython的包放到jython,他們不沖突嗎?一個是java編寫實現的一個是c編寫實現的 支持(0) 反對(0)
</div></div></div><div class="feedbackItem"><div class="feedbackListSubtitle"><div class="feedbackManage">
</div><!-- Title -->
#24樓
<!-- PostDate -->
2018-09-20 17:36
<!--NameLink--><a id="a_comment_author_4072640" href="https://www.cnblogs.com/lmm361027282/" target="_blank">廖昫</a><div class="feedbackCon">
我安裝了一個windows版本的,你的意思是需要重新下載這些第三方包,比如numpy gensim這些第三方庫我試著用pip安裝,他提示說已經存在,路徑指在Anaconda 3.6.5,因為我有一個Anaconda 3.6.5的版本,這是我用來做深度學習開發的python環境 支持(0) 反對(0)
</div></div></div><div class="feedbackItem"><div class="feedbackListSubtitle"><div class="feedbackManage">
</div><!-- Title -->
#25樓
[樓主]
<!-- PostDate -->
2018-09-21 08:28
<!--NameLink--><a id="a_comment_author_4073063" href="https://www.cnblogs.com/nuccch/" target="_blank">2Simple</a><div class="feedbackCon">
@ 廖昫我建議你先搞清楚Python為什么會存在多個語言版本吧?
我回答你的跟你理解的不是一個東西,畢竟不是面對面溝通。理論上講,不論安裝哪個語言版本的Python,都應該可以正常解決依賴問題。我告訴你的方式可能是一個迂回的解決方式,也可能只適合在我的場景。
我建議你先解決基礎的疑問,語言僅僅是工具。 支持(0) 反對(0) https://pic.cnblogs.com/face/722072/20190303092130.png
</div></div></div><div class="feedbackItem"><div class="feedbackListSubtitle"><div class="feedbackManage">
</div><!-- Title -->
#26樓
<!-- PostDate -->
2018-09-21 09:12
<!--NameLink--><a id="a_comment_author_4073109" href="https://www.cnblogs.com/lmm361027282/" target="_blank">廖昫</a><div class="feedbackCon">
是,真心感謝兄弟這么一直跟我溝通,早上特意查了為什么python存在這么版本,也算是了解了,其實之前我一直弄錯了,之前一直用Anaconda做算法,其實它是Cpython,現在要架構服務器,語言是java,那運行環境肯定是需要用Jpython,只是現在jpython是2.7,算是很低的版本,而Anaconda我的是3.6.5的,首先安裝的包版本都不一樣,其次我一直在java里面調用Anaconda的python.exe去執行,肯定不多,所以現在其實兩件事情,安裝Jpython,找各自對應的庫包版本真感謝兄弟,我相信這個問題肯定也困擾很多需要用java調用python和單純用python做算法的人,經過兄弟這么多耐心地回答我的問題,也給遇到同樣問題的人提供解決方案。 支持(1) 反對(0)
</div></div></div><div class="feedbackItem"><div class="feedbackListSubtitle"><div class="feedbackManage">
</div><!-- Title -->
#27樓
[樓主]
<!-- PostDate -->
2018-09-21 10:30
<!--NameLink--><a id="a_comment_author_4073257" href="https://www.cnblogs.com/nuccch/" target="_blank">2Simple</a><div class="feedbackCon">
@ 廖昫對你有幫助就好,不用客氣~ 支持(0) 反對(0) https://pic.cnblogs.com/face/722072/20190303092130.png
</div></div></div><div class="feedbackItem"><div class="feedbackListSubtitle"><div class="feedbackManage">
</div><!-- Title -->
#28樓
<span id="comment-maxId" style="display:none">4073538</span><span id="comment-maxDate" style="display:none">2018/9/21 下午3:06:10</span><!-- PostDate -->
2018-09-21 15:06
<!--NameLink--><a id="a_comment_author_4073538" href="https://www.cnblogs.com/lmm361027282/" target="_blank">廖昫</a><div class="feedbackCon">
我知道我這邊有一個很嚴重的問題,就是a.py無法調用b.py,就像你寫的那個from calculator_clazz import Calculator,這句都會說找不到calculator_clazz,同樣在numpy也存在調用另外一個py文件,肯定說找不到
你是什么環境?為什么可以調用另外的.py文件?我是win10,會不會這個問題?如果這個解決,那基本上問題解決了 支持(0) 反對(0)
</div></div></div>
刷新評論刷新頁面返回頂部 注冊用戶登錄后才能發表評論,請 登錄 或 注冊, 訪問 網站首頁。 【推薦】超50萬行VC++源碼: 大型組態工控、電力仿真CAD與GIS源碼庫【活動】京東云服務器_云主機低于1折,低價高性能產品備戰雙11
【推薦】天翼云雙十一提前開搶,1核1G云主機3個月僅需59元
【活動】魔程社區技術沙龍訓練營—大數據主題專場等你來報名
【優惠】騰訊云 11.1 1智惠上云,爆款提前購與雙11活動同價
【福利】個推四大熱門移動開發SDK全部免費用一年,限時搶!
相關博文:
· Python與Java之間的相互調用——Jython
· 在java中調用python
· 在Java中調用Python代碼
· python系列一——python特點以及和java不同的運行機制
· 【一:定義】python 簡介
? 更多推薦...
<div id="google_ads_iframe_/1090369/C2_0__container__" style="border: 0pt none;"><iframe id="google_ads_iframe_/1090369/C2_0" title="3rd party ad content" name="google_ads_iframe_/1090369/C2_0" width="468" height="60" scrolling="no" marginwidth="0" marginheight="0" frameborder="0" srcdoc="" style="border: 0px; vertical-align: bottom;" data-google-container-id="2" data-load-complete="true"></iframe></div></div>
</div>
<div id="under_post_kb">
最新 IT 新聞: · 李國慶已向法院提交訴狀和俞渝離婚 :要求平分當當網股權
· 1024,禿如其來的碼農圖鑒
· 專訪華為何剛:華為Mate30 5G系列將成“核彈級爆款”
· NASA計劃2023年建成LLISSE金星表面探測器并展開測試
· 高速公路告別“重名”現象,高德百度等協同更新數據
? 更多新聞...
總結
以上是生活随笔為你收集整理的java中调用python的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python多进程 AttributeE
- 下一篇: 镜像 国内源 汇总