本文目錄一覽:
怎麼在java的flink中調用python程序?
一、在java類中直接執行python語句
import org.python.util.PythonInterpreter;
public class FirstJavaScript {
public static void main(String args[]) {
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec(“days=(‘mod’,’Tue’,’Wed’,’Thu’,’Fri’,’Sat’,’Sun’); “);
interpreter.exec(“print days[1];”);
}// main
}
調用的結果是Tue,在控制台顯示出來,這是直接進行調用的。
二、在java中調用本機python腳本中的函數
首先建立一個python腳本,名字為:my_utils.py
def adder(a, b):
return a + b
然後建立一個java類,用來測試,
java類代碼 FirstJavaScript:
import org.python.core.PyFunction;
import org.python.core.PyInteger;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;
public class FirstJavaScript {
public static void main(String args[]) {
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile(“C:\\Python27\\programs\\my_utils.py”);
PyFunction func = (PyFunction) interpreter.get(“adder”,
PyFunction.class);
int a = 2010, b = 2;
PyObject pyobj = func.__call__(new PyInteger(a), new PyInteger(b));
System.out.println(“anwser = ” + pyobj.toString());
}// main
}
得到的結果是:anwser = 2012
三、使用java直接執行python腳本
建立腳本inputpy
#open files
print ‘hello’
number=[3,5,2,0,6]
print number
number.sort()
print number
number.append(0)
print number
print number.count(0)
print number.index(5)
建立java類,調用這個腳本:
import org.python.util.PythonInterpreter;
public class FirstJavaScript {
public static void main(String args[]) {
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile(“C:\\Python27\\programs\\input.py”);
}// main
}
得到的結果是:
hello
[3, 5, 2, 0, 6]
[0, 2, 3, 5, 6]
[0, 2, 3, 5, 6, 0]
2
3
如何在Java中調用Python代碼
Jython(原JPython),是一個用Java語言寫的Python解釋器。在沒有第三方模塊的情況下,通常選擇利用Jython來調用Python代碼,它是一個開源的JAR包,你可以到官網下載一個HelloPython程序importorg.python.util.PythonInterpreter;publicclassHelloPython{publicstaticvoidmain(String[]args){PythonInterpreterinterpreter=newPythonInterpreter();interpreter.exec(“print(‘hello’)”);}}什麼是PythonInterpreter?它的中文意思即是“Python解釋器”。我們知道Python程序都是通過解釋器來執行的,我們在Java中創建一個“解釋器”對象,模擬Python解釋器的行為,通過exec(“Python語句”)直接在JVM中執行Python代碼,上面代碼的輸出結果為:hello在Jvm中執行Python腳本interpreter.execfile(“D:/labs/mytest/hello.py”);如上,將exec改為execfile就可以了。需要注意的是,這個.py文件不能含有第三方模塊,因為這個“Python腳本”最終還是在JVM環境下執行的,如果有第三方模塊將會報錯:javaImportError:Nomodulenamedxxx僅在Java中調用Python編寫的函數先完成一個hello.py代碼:defhello():return’Hello’在Java代碼中調用這個函數:importorg.python.core.PyFunction;importorg.python.core.PyObject;importorg.python.util.PythonInterpreter;publicclassHelloPython{publicstaticvoidmain(String[]args){PythonInterpreterinterpreter=newPythonInterpreter();interpreter.execfile(“D:/labs/hello.py”);PyFunctionpyFunction=interpreter.get(“hello”,PyFunction.class);//第一個參數為期望獲得的函數(變量)的名字,第二個參數為期望返回的對象類型PyObjectpyObject=pyFunction.__call__();//調用函數System.out.println(pyObject);}}上面的代碼執行結果為:Hello即便只是調用一個函數,也必須先加載這個.py文件,之後再通過Jython包中所定義的類獲取、調用這個函數。如果函數需要參數,在Java中必須先將參數轉化為對應的“Python類型”,例如:__call__(newPyInteger(a),newPyInteger(b))a,b的類型為Java中的int型,還有諸如:PyString(Stringstring)、PyList(Iteratoriter)等。詳細可以參考官方的api文檔。包含第三方模塊的情況:一個手寫識別程序這是我和舍友合作寫的一個小程序,完整代碼在這裡:,界面上引用了corejava上的一段代碼。Python代碼是舍友寫的,因為在Python程序中使用了第三方的NumPy模塊,導致無法通過Jython執行。下面這個方法純粹是個人思路,沒有深入查資料。核心代碼如下:importjava.io.*;classPyCaller{privatestaticfinalStringDATA_SWAP=”temp.txt”;privatestaticfinalStringPY_URL=System.getProperty(“user.dir”)+”\\test.py”;publicstaticvoidwriteImagePath(Stringpath){PrintWriterpw=null;try{pw=newPrintWriter(newFileWriter(newFile(DATA_SWAP)));}catch(IOExceptione){e.printStackTrace();}pw.print(path);pw.close();}publicstaticStringreadAnswer(){BufferedReaderbr;Stringanswer=null;try{br=newBufferedReader(newFileReader(newFile(DATA_SWAP)));answer=br.readLine();}catch(FileNotFoundExceptione){e.printStackTrace();}catch(IOExceptione){e.printStackTrace();}returnanswer;}publicstaticvoidexecPy(){Processproc=null;try{proc=Runtime.getRuntime().exec(“python”+PY_URL);proc.waitFor();}catch(IOExceptione){e.printStackTrace();}catch(InterruptedExceptione){e.printStackTrace();}}//測試碼publicstaticvoidmain(String[]args)throwsIOException,InterruptedException{writeImagePath(“D:\\labs\\mytest\\test.jpg”);execPy();System.out.println(readAnswer());}}實際上就是通過Java執行一個命令行指令。
怎麼使用java運行python腳本?
如果是jython,也就是運行在Jvm上的python的話,可以使用JSR223,JDK1.6已經包含了該擴展包。JSR223是一個用於解析多種腳本語言的庫包,其中包括Jython。除了JSR223包之外,還需要jython-engine.jar包。
ScriptEngine engine = new ScriptEngineManager().getEngineByName(“python”);
try
{
engine.eval(new FileReader(“./script/listing.py”));
}
catch(ScriptException se)
{
}
catch(IOException ie)
{
}
或者參考:
很久之前用過ScriptEngine,對在Jvm上的腳本語言比如jruby,jython,groovy等支持性都很好,有點忘記了。
java怎麼點用python腳本?
首先得聲明一下,java是java,python是python,你用java得環境跑python這不是找麻煩嗎,但是並不是說不行,java有一個Jpython得庫,你可以下載一下,這方面原理設計jni技術,建議了解一下,如果單純想運行一個腳本可以找Jpython得api文檔看看
原創文章,作者:ETZGA,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/316133.html