简体   繁体   中英

Java - ProcessBuilder is not outputting my python file

Some context: I'm trying to make a GUI on java and have python code run once I click a button on the GUI. For example if I press start on the java GUI, it will run the python code on file .py.

Why is it not outputting anything? You can also try this by creating a test python file and just inputting your own file location into the code below.

Code so far:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import javax.swing.JFrame;

public class main_gui extends JFrame {
     public static void main(String[] args) throws Exception {

        ProcessBuilder builder = new ProcessBuilder("cmd.exe",
                "cd \"G:\\...Javaa\\filetranslatorapplication\\file_translator_app.py");
        builder.redirectErrorStream(true);
        Process p = builder.start();
        BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line;
        while (true) {
            line = r.readLine();
            if (line == null) {
                break;
            }
            System.out.println(line);
        }
    }
}

Two things to keep in mind:

  1. The python file in NOT in the same place as this java file.
  2. The java file and python file are both on a usb, hence the "G:\\..".

Also, if anyone has a better way of running python code through java gui, please feel free to point me in the right direction.

Your process simply does not make sense.

It simply spawn a cmd , and cd to an invalid directory (as it is a file).

What you want is probably

cmd /c python g:\your\path\foo.py

or

cmd /c g:\your\path\foo.py

or simply

may\be\full\path\is\needed\python g:\your\path\foo.py

So, your code should look like:

ProcessBuilder builder 
    = new ProcessBuilder("cmd.exe", "/c", "python", "g:\\yourpath\\file_translator_app.py");
// or 
// = new ProcessBuilder("python", "g:\\yourpath\\file_translator_app.py");
// or 
// = new ProcessBuilder("cmd", "/c", "g:\\yourpath\\file_translator_app.py");

The following should work for you:

    ProcessBuilder builder = new ProcessBuilder("cmd",
            "/c \"G: && python Javaa\\filetranslatorapplication\\file_translator_app.py\"");

This gets executed when I run my Java application from a different drive. But, for you, if it is the same drive, need not switch to G: . You may execute the py file with python command.

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