簡體   English   中英

如何使用 java (Runtime.getRuntime().exec()) 啟動 python 程序

[英]How to start a python program using java (Runtime.getRuntime().exec())

我正在編寫一個程序,該程序需要在 java 代碼的 rest 代碼運行之前啟動 python 腳本。 但是,我找不到解決問題的方法。 如果有人可以提出解決我面臨的問題的方法,我將不勝感激。

代碼(我需要在注釋“start python”下的部分幫助):

import java.io.IOException;

//makes it easier for user to
//select game/start python
public class gameselect {
    public static void main(String args[]) throws IOException {
        //start python
        try {
            String cmd = "python ngramcount.py";
            Process process = Runtime.getRuntime().exec(cmd);
            process.getInputStream();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        
        //select game
        try {
            Scanner in = new Scanner (System.in);
            game1 g = new game1();
            game2 f = new game2();
            int choice = 0;
            System.out.println("Welcome to TranslateGame!");
            System.out.println("Type 1 for game1 (words) or 2 for game2 (phrases)");
            while (choice != 1 && choice != 2) {
                choice = in.nextInt();
                if (choice != 1 && choice != 2) {
                    System.out.println("No game associated with that number.");
                }
            }
            if (choice == 1) {
                g.game1();
            }
            else if (choice == 2) {
                f.game2();
            }
        }
        catch(IOException e) {
            System.out.println("No.");
        }
    }
}

這是一些您可能可以開始工作的代碼。 我還對其進行了評論並提供了一些參考鏈接,以幫助您了解代碼在做什么。

    public static void main(String[] args) throws IOException {

    // I'm using the absolute path for my example.
    String fileName = "C:\\Users\\yourname\\Desktop\\testing.py";

    // Creates a ProcessBuilder
    // doc: https://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html
    ProcessBuilder pb = new ProcessBuilder("python", fileName);

    pb.redirectErrorStream(true); // redirect error stream to a standard output stream
    Process process = pb.start(); // Used to start the process

    // Reads the output stream of the process.
    BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    String line; // this will be used to read the output line by line. Helpful in troubleshooting.
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }



}

暫無
暫無

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

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