Java调用Python语言及第三方Python库


#pic_center =400x
系列文章:


文章目录


1、导入依赖

<!--Python&Java-->
        <dependency>
            <groupId>org.python</groupId>
            <artifactId>jython-standalone</artifactId>
            <version>2.7.2</version>
        </dependency>

2、在java中直接执行python代码片段
通过上面这种方式执行python代码片段,实际上是通过Jpython来实现的,这种方式能执行的python代码片段比较有限,都是一些最原始的python命令,很多包不能用,例如执行pythonInterpreter.exec(“import pandas as pd”); 都会报错。所以这种方式一般不推荐

package com.song.mywj.py;

import org.python.util.PythonInterpreter;

import java.io.IOException;

public class TestPy {
    public static void main(String[] args) throws IOException, InterruptedException {


        Mytest();
    }
    public static void Mytest () throws IOException, InterruptedException {
        Process proc = Runtime.getRuntime().exec("python  E:\\code\\deeplea\\pytorchlearn\\learn\\plt\\test.py");
        proc.waitFor();
        PythonInterpreter interpreter = new PythonInterpreter();
        interpreter.exec("a=[5,2,3,9,4,0]; ");
        interpreter.exec("print(sorted(a));");  //此处python语句是3.x版本的语法
        interpreter.exec("print sorted(a);");   //此处是python语句是2.x版本的语法

    }

Java调用Python程序方法总结

3、通过Runtime.getRuntime().exec()方法来执行python脚本

package com.song.mywj.py;


import java.io.IOException;

public class TestPy {
    public static void main(String[] args) throws IOException, InterruptedException {


        Mytest();
    }
    public static void Mytest () throws IOException, InterruptedException {
        Process proc ;
        String compiler = "D:\\devementtool\\Anaconda3-202105\\python.exe";
        String rootPath = "E:\\code\\deeplea\\pytorchlearn\\learn\\plt\\";
        String program = "test.py";
        String commond = compiler+" "+rootPath+program;
        proc = Runtime.getRuntime().exec(commond);
        proc.waitFor();
    }
}

原python脚本

# 导入功能包,产生数据
import numpy as np
import matplotlib.pyplot as plt
import statsmodels.api as sm

nsample = 20 # 20个样本点
x = np.linspace(0,10,nsample) # 从0到20之间选择20个数(等距)
print(x)

# 加一列1,为了与常数项进行组合
X = sm.add_constant(x)
print(X)
# 产生β0与β1(真实情况)
beta = np.array([2,5])
print(beta)
# 误差项(设置抖动,为了让数据更真实)
e = np.random.normal(size=nsample)
print(e)
# 实际值y
y = np.dot(X,beta) + e
print(y)
# 最小二乘法
model = sm.OLS(y,X)
# 拟合数据
res = model.fit()
# 计算的回归系数β0和β1
print(res.params)
# 产生全部结果
res.summary()
# 拟合的估计值
y_ = res.fittedvalues
print(y_)
# 拟合的估计值
y_ = res.fittedvalues
print(y_)
fig, ax = plt.subplots(figsize=(8,6))
ax.plot(x,y,'o',label='data') # 原始数据
ax.plot(x,y_,'r--',label='test') # 拟合数据
ax.legend(loc='best')
plt.show()

在java中调用python程序

java调用外部程序(Runtime.getRuntime().exec)详解

    @Test
    void contextLoads() {

        Process proc;
        try {
        	/*
			附加:
			String[] args1=new String[]{"/home/huan/anaconda2/bin/python","/home/huan/myfile/pythonfile/helloword.py"};
            Process pr=Runtime.getRuntime().exec(args1);
			String数组里的那一行很重要
			首先一定要设置好你所使用的python的位置,切记不要直接使用python,
			因为系统会默认使用自带的python,所以一定要设置好你所使用的python的位置,
			否则可能会出现意想不到的问题
			(比如说我使用的是anaconda中的python,而ubuntu系统会默认调用自带的python,
			而我自带的python中并没有numpy库,所以会造成相应的代码不会执行的问题,所以设置好python的位置是很重要的)。
			还有就是要设置好py文件的位置,使用绝对路径。在这里插入代码片
       还有就是可以看出,此方法可以满足我们python代码中调用第三方库的情况,简单实用。
			*/
//        	 pythone执行环境
        	String pyEnv = "D:\\devementtool\\Anaconda3-202105\\python.exe";
//        	要执行的py代码
        	String program = "E:\\code\\deeplea\\pytorchlearn\\shiyan\\single\\test.py";
        	String a="aa";
        	String b="bb";
//        	参数集合
        	String[] args = new String[] {pyEnv, program,a,b,"呵呵呵"};
            proc = Runtime.getRuntime().exec(args);
//            输出到控制台有中文,使用utf-8还是乱码 , 使用GBK就可以
            BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream(),"GBK"));
            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();
        }
    }

# coding:utf-8
import numpy as np
import sys
# E:\code\deeplea\pytorchlearn\shiyan\single\test.py
if __name__ == '__main__':
    a = np.ones(3)
    print(a)
    print('恭喜您!java调用python代码成功')
    print('脚本名为:%s' % (sys.argv[0]))
    print('传入的参数为:')
    for i in range(1, len(sys.argv)):
        print('参数:%s' % (sys.argv[i]))

在这里插入图片描述
【Java】使用Java调用Python的四种方法

  • 3
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值