首页 > 解决方案 > 如何从我的 Java 运行 python 2.7 代码?

问题描述

我有一个 Java Swing 类,我希望我的 Java 应用程序在单击按钮后运行本地 python 程序。以下代码不运行我创建的可执行 python。

 private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    try {
        // TODO add your handling code here:
        Process process = 
        Runtime.getRuntime().exec("C:\\Users\\User\\Desktop\\hello.exe");
    } catch (IOException ex) {
        Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
    }

}     

我什至尝试使用以下命令运行 python 脚本文件:

     private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    try {

        Process p= Runtime.getRuntime().exec("C:\\Python27\\python.exe \"C:\\Users\\User\\Desktop\\hello.py\"");
    } catch (IOException ex) {
        Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
    }

}      

我没有错误,但这项工作也没有。我可以使用相同的语法运行记事本等应用程序,但是我不能使用 python,我不确定如何解决这个问题。Ps 我的环境变量中确实有 Python 2.7 PATH。此外,以上只是按钮执行的操作的方法。我的完整程序中有所有其他方法和主类。

标签: javapythonpython-2.7cmd

解决方案


    Process p= Runtime.getRuntime().exec("cmd /c /K \"C:\\Python27\\python.exe C:\\Users\\User\\Desktop\\hello.py\"");

这样做..从cmd调用Python


我尝试了这个简单的示例,它对我有用... 文件:CallPython.java&hello.py

调用Python.java

import java.util.*;
import java.io.*;

class CallPython{

    public static void main(String args[]){

       try{
            Process proc= Runtime.getRuntime().exec("python hello.py");
            BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));

            /*
            BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));

            // read the output from the command
            System.out.println("Here is the standard output of the command:\n");
            String s = null;
            while ((s = stdInput.readLine()) != null) {
                System.out.println(s);
            }
            */

            stdInput.lines().forEach(System.out::println);
        }
        catch(IOException e){
            System.err.println("Error occured while executing an external process...");
        }
    }
}

你好.py

print('Hello...from python script');

输出:

 Hello...from python script

输出片段


推荐阅读