首页 > 编程知识 正文

用java执行python,java程序怎么执行

时间:2023-12-27 22:27:18 阅读:325858 作者:URBJ

本文目录一览:

怎么在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文档看看

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。