簡體   English   中英

如何從Java運行python 2.7代碼?

[英]How do I run a python 2.7 code from my Java?

我有一個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。 同樣,以上只是按鈕執行操作的方法。 我的整個程序中都有所有其他方法和主類。

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

這樣..從cmd調用Python


我嘗試了這個簡單的示例,並且對我CallPython.java ... Files: CallPython.javahello.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...");
        }
    }
}

你好

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

輸出:

 Hello...from python script

輸出片段

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM