Python函数proc python函数print( 三 )


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()passexcept Exception as identifier:print(identifier)passpassserversocket.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 = clientsocketself._recvsize = recvsizeself._encoding = encodingpassdef 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]breaksendmsg = Image.open(msg)# 发送数据self._socket.send(("%s"%sendmsg).encode(self._encoding))passexcept Exception as identifier:self._socket.send("500".encode(self._encoding))print(identifier)passfinally:self._socket.close()print("任务结束.....")passdef __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 stubtry {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("远程接口调用结束.");}}}

推荐阅读