如何从Java运行python 2.7代码?

问题描述 投票:1回答:1

我有一个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,我不确定如何解决这个问题。附:我的环境变量中有Python 2.7 PATH。此外,以上只是按钮执行操作的方法。我的完整程序中包含所有其他方法和主要类。

java python python-2.7 cmd
1个回答
0
投票
    Process p= Runtime.getRuntime().exec("cmd /c /K \"C:\\Python27\\python.exe C:\\Users\\User\\Desktop\\hello.py\"");

这样做..从cmd调用Python


我尝试了这个简单的例子,它对我有用......文件:qazxsw poi&qazxsw poi

call Python.Java

CallPython.java

hello.朋友

hello.py

输出:

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...");
        }
    }
}

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

© www.soinside.com 2019 - 2024. All rights reserved.