java运行python代码(java运行python文件)
如何在java工程里运行一个python脚本?
可以使用jython
方法参考如下
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile("uar/local/xxx.py");
//pyFunction :py中方法名
PyFunction func = (PyFunction)interpreter.get("型兄察pyFunction",PyFunction.class);
Integer a = 1?尘手 ? ? ? ?
Integer b = 2
// py中方法传参
PyObject pyobj = func.__call__(new PyInteger(a), new PyInteger(b));
System.out.println("卜茄anwser = " + pyobj.toString());
怎么在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,也就是运行在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怎么调python?下面就一起来了解一下吧~
java调python主要有两种方法:1.使用Runtime.getRuntime()执行脚本文件;2. 将python脚本写成进程为java提供服务,下面是具体的方法介绍:
第一种:使用Runtime.getRuntime()执行脚本文件
先建立python脚本文件 demo.py
import?numpy?as?np a?=?np.arange(12).reshape(3,4)print(a)
java调用python程序并输出该结果
import?java.io.BufferedReader;import?java.io.IOException;import?java.io.InputStreamReader;public?class?Demo?{ ????public?static?void?main(String[]?args)?{ ????????//?TODO?Auto-generated?method?stub ????????Process?proc; ????????try?{ ????????????proc?=?Runtime.getRuntime().exec("python?D:\\demo.py");//?执行py文件 ????????????//用输入输出流来截取结果 ????????????BufferedReader?in?=?new?BufferedReader(new?InputStreamReader(proc.getInputStream())); ????????????String?line?=?null; ????????????while?((line?=?in.readLine())?!=?null)?{ ?????锋清???????????System.out.println(line); ????????????} ????????????in.close(); ????????????proc.waitFor(); ????????}?catch?(IOException?e)?{ ????????????e.printStackTrace(); ????????}?catch?(InterruptedException?e)?{ ????????????e.printStackTrace(); ????????}? ????}}
如若向python程序中函数传递参数并执行出结果,下面就举一例来说明一下。
同样建立python脚本文件demo2.py
import?sys def?func(a,b): ????return?(a+b)if?__name__?==?'__main__': ????a?=?[] ????for?i?in?range(1,?len(sys.argv)): ????????a.append((int(sys.argv[i]))) ????print(func(a[0],a[1]))
其中sys.argv用于获取参数url1,url2等。而sys.argv[0]代表python程序名,所以列表从1开始读取参数。
以上代码实现一个两个链基桐数做加法的程序,下面看看在java中怎么传递函数参数,代码如下:
int?a?=?18;int?b?=?23;try?{ ????String[]?args?=?new?String[]?{?"python",?"D:\\demo2.py",?String.valueOf(a),?String.valueOf(b)?}; ????Process?proc?=?Runtime.getRuntime().exec(args);//?执行py文件棚坦 ????BufferedReader?in?=?new?BufferedReader(new?InputStreamReader(proc.getInputStream())); ????String?line?=?null; ????while?((line?=?in.readLine())?!=?null)?{ ????????System.out.println(line); ????} ????in.close(); ????proc.waitFor();}?catch?(IOException?e)?{ ????e.printStackTrace();}?catch?(InterruptedException?e)?{ ????e.printStackTrace();}
其中args是String[] { “python”,path,url1,url2 }; ,path是python程序所在的路径,url1是参数1,url2是参数2,以此类推。
2. 将python脚本写成进程为java提供服务
python脚本文件如下:
import?socketimport?sysimport?threadingimport?numpy?as?npfrom?PIL?import?Imagedef?main(): ????#?创建服务器套接字 ????serversocket?=?socket.socket(socket.AF_INET,socket.SOCK_STREAM) ????#?获取本地主机名称 ????host?=?socket.gethostname() ????#?设置一个端口 ????port?=?12345 ????#?将套接字与本地主机和端口绑定 ????serversocket.bind((host,port)) ????#?设置监听最大连接数 ????serversocket.listen(5) ????#?获取本地服务器的连接信息 ????myaddr?=?serversocket.getsockname() ????print("服务器地址:%s"%str(myaddr)) ????#?循环等待接受客户端信息 ????while?True: ????????#?获取一个客户端连接 ????????clientsocket,addr?=?serversocket.accept() ????????print("连接地址:%s"?%?str(addr)) ????????try: ????????????t?=?ServerThreading(clientsocket)#为每一个请求开启一个处理线程 ????????????t.start() ????????????pass ????????except?Exception?as?identifier: ????????????print(identifier) ????????????pass ????????pass ????serversocket.close() ????passclass?ServerThreading(threading.Thread): ????#?words?=?text2vec.load_lexicon() ????def?__init__(self,clientsocket,recvsize=1024*1024,encoding="utf-8"): ????????threading.Thread.__init__(self) ????????self._socket?=?clientsocket ????????self._recvsize?=?recvsize ????????self._encoding?=?encoding????????pass ????def?run(self): ????????print("开启线程.....") ????????try: ????????????#接受数据 ????????????msg?=?'' ????????????while?True: ????????????????#?读取recvsize个字节 ????????????????rec?=?self._socket.recv(self._recvsize) ????????????????#?解码 ????????????????msg?+=?rec.decode(self._encoding) ????????????????#?文本接受是否完毕,因为python?socket不能自己判断接收数据是否完毕, ????????????????#?所以需要自定义协议标志数据接受完毕 ????????????????if?msg.strip().endswith('over'): ????????????????????msg=msg[:-4] ????????????????????break ??????????? ????????????sendmsg?=?Image.open(msg) ????????????#?发送数据 ????????????self._socket.send(("%s"%sendmsg).encode(self._encoding)) ????????????pass ????????except?Exception?as?identifier: ????????????self._socket.send("500".encode(self._encoding)) ????????????print(identifier) ????????????pass ????????finally: ????????????self._socket.close()? ????????print("任务结束.....") ???????? ????????pass ????def?__del__(self): ????????passif?__name__?==?"__main__": ????main()
在java代码中访问python进程的代码: package?hello;import?java.lang.System;import?java.io.BufferedReader;import?java.io.IOException;import?java.io.InputStreamReader;import?java.net.InetAddress;import?java.net.Socket;import?java.io.OutputStream;import?java.io.PrintStream;import?java.io.InputStream;public?class?hello?{ ????public?static?void?main(String[]?args){ ????????//System.out.println("Hello?World!"); ????????//?TODO?Auto-generated?method?stub ????????try?{ ????????????InetAddress?addr?=?InetAddress.getLocalHost(); ????????????String?host=addr.getHostName(); ????????????//String?ip=addr.getHostAddress().toString();?//获取本机ip ????????????//log.info("调用远程接口:host="+ip+",port="+12345); ????????????//?初始化套接字,设置访问服务的主机和进程端口号,HOST是访问python进程的主机名称,可以是IP地址或者域名,PORT是python进程绑定的端口号 ????????????Socket?socket?=?new?Socket(host,12345); ????????????//?获取输出流对象 ????????????OutputStream?os?=?socket.getOutputStream(); ????????????PrintStream?out?=?new?PrintStream(os); ????????????//?发送内容 ????????????out.print(?"F:\\xxx\\0000.jpg"); ????????????//?告诉服务进程,内容发送完毕,可以开始处理 ????????????out.print("over"); ????????????//?获取服务进程的输入流 ????????????InputStream?is?=?socket.getInputStream(); ????????????BufferedReader?br?=?new?BufferedReader(new?InputStreamReader(is,"utf-8")); ????????????String?tmp?=?null; ????????????StringBuilder?sb?=?new?StringBuilder(); ????????????//?读取内容 ????????????while((tmp=br.readLine())!=null) ????????????????sb.append(tmp).append('\n'); ????????????System.out.print(sb); ????????????//?解析结果 ????????????//JSONArray?res?=?JSON.parseArray(sb.toString()); ????????}?catch?(IOException?e)?{ ????????????e.printStackTrace(); ????????}finally?{ ????????????try?{if(socket!=null)?socket.close();}?catch?(IOException?e)?{} ????????????System.out.print("远程接口调用结束."); ????????} ??????}}
如何在Java中调用Python代码
方法如信悉雹下:
package com.lyz.test.jython;
import org.python.util.PythonInterpreter;
/**
* 第一个Jython程序
* @author liuyazhuang
*
*/滑帆
public class FirstJythonScript {
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];");
}
}
如何在 Java 中调用 Python 代码
可以念没用Python的扩展来仔桐纳实现。Python本来是C实现的,封装二进制兼容的C++是很容易的。Java的话得通过JNI来实现,就是说在Python扩展里用C调用Java。另外,轮坦也可以写一个TCP服务来包装C++/Java的接口,通过网络来调用,这样更通用。