简体   繁体   中英

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

I am writing a program that requires the starting of a python script before the rest of the java code runs. However, I cannot find a solution to my issues. I would appreciate if someone could suggest a solution to the problem I am facing.

Code (I need help on the part under the comment "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.");
        }
    }
}

Here is some code that you might be able to get to work. I also commented it and provided some reference links to help you understand what the code is doing.

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



}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM