JAVA如何调用python

以下代码想通过测试,必须有一个前提:电脑上安装了Python环境。不太习惯说废话,直接上代码了。

以下是用于测试的python代码(mytest.py):

# 因为用户到了参数处理,所以需要引用
import argparse

def test(uname, msg):
    return uname + ',你好,你发来的消息是:' + msg

def main():
    parser = argparse.ArgumentParser(description="调用测试")
    # 此处uname的命名,在调用时会用到
    parser.add_argument("--uname", type=str, help="传入的用户名")
    parser.add_argument("--msg", type=str, help="传入的消息")

    args = parser.parse_args()

    result = test(uname=args.uname, msg=args.msg)

    # 输出返回值,若有调用,对方可获取
    print(result)


if __name__ == "__main__":
    main()

以下是Java代码:

public void test() {
        try{
            // 工作目录
            String currentDirectory = System.getProperty("user.dir");
            // 注意开头的testPython根据实际情况进行调整,因为我将Python代码和Java代码放入到了同一个项目中,所以这么写
            String pythonScriptRelativePath = "testPython/src/main/java/com/mytest.py";
            // py文件的具体路径
            String pythonScriptPath = currentDirectory + File.separator + pythonScriptRelativePath;
            // 执行 Python 脚本,带有参数
            ProcessBuilder processBuilder = new ProcessBuilder("python", pythonScriptPath,
                    "--uname", "Vincent Lu", "--msg", "收到消息了吗?");

            // 读取脚本的标准输出
            Process process = processBuilder.start();
            InputStream stdout = process.getInputStream();
            // 此处,我用了GBK,大家可根据实际情况进行调整
            BufferedReader reader = new BufferedReader(new InputStreamReader(stdout, "GBK"));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println("收到Python的返回值: " + line);
            }

            // 若发生错误,会执行以下内容
            InputStream stderr = process.getErrorStream();
            BufferedReader errorReader = new BufferedReader(new InputStreamReader(stderr));
            while ((line = errorReader.readLine()) != null) {
                System.out.println("错误内容: " + line);
            }

            // 等待进程结束并获取退出值
            int exitValue = process.waitFor();
            System.out.println("Exit value: " + exitValue);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

关于参数,有一点需要注意一下,若Python想接收一个dict类型的参数,在parser.add_argument("--dictData", type=str, help="传入的dict类型数据,理论上是一个JSON") 配置中,type依旧可以使用str类型,但是,在使用过程中,需要eval转换一下。如下:

result = test(dictData=eval(args.dictData))

更有趣的是,在JAVA中想传递JSON串,我必须得写成

String speedJson = "{\\\"SPEED\\\":[35, 95, 92, 92, None, 90, 93, 90, None, None, None, None, None, None, None, None, None]}"

我不太明白,为什么要加3个斜杠。

好啦,就到这里吧,我是来自北京天码科技的卢泽。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值