java引用python时,in.readLine()为null,proc.waitFor()为1

文章讲述了在Java中使用Runtime.getRuntime().exec()方法执行Python脚本时遇到的问题,由于Python脚本依赖第三方库的.dll文件,直接复制到java文件目录下并未解决问题。解决方案是明确指定.dll文件的路径。最终,通过在执行Python脚本时传入.dll文件所在目录,成功解决了这个问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

之前查询了java去引用python代码的方法,因为python中使用了第三方库,选择使用

Runtime.getRuntime().exec() 

这个方法体,但是还是一直报错说java代码没有对应的.dll文件,之前草率的把.dll文件直接复制到java文件下,还是不对,查询网络发现因为java和python运行代码的机制不同,最后发现需要单独引入对应.dll的文件所在路径,现已完美解决,代码展示如下:

public class javaPython {
    public static void main(String[] args) throws Exception{
        try {
            Process proc = Runtime.getRuntime().exec("python D:\\finally02.py",null,new File("D:\\USBCAN-I"));// 执行py文件以及dll所在的地址
            BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            BufferedReader error = new BufferedReader(new InputStreamReader(proc.getErrorStream()));

            System.out.println("Python gram out");
            String line = null;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
    //此处是为了看代码报错原因
            System.out.println("Python gram error");
            while ((line = error.readLine()) != null) {
                System.out.println(line);
            }

            in.close();
            proc.waitFor();
            System.out.println(proc.waitFor());
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值