java程序中是否可以嵌入python程序?

Python013

java程序中是否可以嵌入python程序?,第1张

可以 有jpython jpython 是吧python 编译成java 字节码 所以 可以调用 实现在java里写python python里写java 只要导入相关的包 架设jpython编译环境就好

Jython(原JPython),是一个用Java语言写的Python解释器。在没有第三方模块的情况下,通常选择利用Jython来调用Python代码,它是一个开源的JAR包,你可以到官网下载一个HelloPython程序importorg.python.util.PythonInterpreterpublicclassHelloPython{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.PyFunctionimportorg.python.core.PyObjectimportorg.python.util.PythonInterpreterpublicclassHelloPython{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=nulltry{pw=newPrintWriter(newFileWriter(newFile(DATA_SWAP)))}catch(IOExceptione){e.printStackTrace()}pw.print(path)pw.close()}publicstaticStringreadAnswer(){BufferedReaderbrStringanswer=nulltry{br=newBufferedReader(newFileReader(newFile(DATA_SWAP)))answer=br.readLine()}catch(FileNotFoundExceptione){e.printStackTrace()}catch(IOExceptione){e.printStackTrace()}returnanswer}publicstaticvoidexecPy(){Processproc=nulltry{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执行一个命令行指令。

如果想把Python写的脚本嵌入到java开发的网站中,需要用system的方式来调用文件,java的Runtime.getRuntime().exec(commandStr)可以调用执行cmd指令:

f1 =  raw_input("input file name")

f2 =  raw_input("input another name")

img1 = cv.imread(f1)

img2 = cv.imread(f2)

#如果是java来调用文件,java获得用户表单里提交的文件名,作为参数传到Python脚本

import sys

f1 = sys.argv[1]

f2 = sys.argv[2]

img1 = cv.imread(f1)

img2 = cv.imread(f2)

#调用的时候,按照脚本名+空格 +参数1 + 参数2的方式来运行就可以了。