zoukankan      html  css  js  c++  java
  • 在Java中调用Python

    直接通过Runtime进行调用

    我们知道,在Java中如果需要调用第三方程序,可以直接通过Runtime实现,这也是最直接最粗暴的做法

    public class InvokeByRuntime {
        /**
         * @param args
         * @throws IOException 
         * @throws InterruptedException 
         */
        public static void main(String[] args) throws IOException, InterruptedException {
            String exe = "python";
            String command = "D:\\calculator_simple.py";
            String num1 = "1";
            String num2 = "2";
            String[] cmdArr = new String[] {exe, command, num1, num2};
            Process process = Runtime.getRuntime().exec(cmdArr);
            InputStream is = process.getInputStream();
            DataInputStream dis = new DataInputStream(is);
            String str = dis.readLine();
            process.waitFor();
            System.out.println(str);
        }
    }
    3
    

    calculator_simple.py:

    # coding=utf-8
    from sys import argv
    
    num1 = argv[1]
    num2 = argv[2]
    sum = int(num1) + int(num2)
    print sum

    显然,在Java中通过Runtime调用Python程序与直接执行Python程序的效果是一样的,可以在Python中读取传递的参数,也可以在Java中读取到Python的执行结果。需要注意的是,不能在Python中通过return语句返回结果,只能将返回值写入到标准输出流中,然后在Java中通过标准输入流读取Python的输出值。

      

  • 相关阅读:
    0401. Binary Watch (E)
    0436. Find Right Interval (M)
    0151. Reverse Words in a String (M)
    1344. Angle Between Hands of a Clock (M)
    0435. Non-overlapping Intervals (M)
    0434. Number of Segments in a String (E)
    0063. Unique Paths II (M)
    0062. Unique Paths (M)
    0100. Same Tree (E)
    0190. Reverse Bits (E)
  • 原文地址:https://www.cnblogs.com/huaobin/p/15692202.html
Copyright © 2011-2022 走看看