Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run python script through Java with files arguments [duplicate]

Tags:

java

python

file

I have a standard Maven project and I want to run the meTypeset script. This script takes 3 args where the second one is a file and the third one is a folder created as output.

This is how the script runs in a cmd:

meTypeset.py docx <input> <output_folder> [options]

This is how I try to run it in Java:

public static void main(String args[]) {
    String[] cmd = {
            "python",
            "resources\\pyscripts\\meTypeset.py",
            "docx",
            "resources\\exampledocs\\example_journal.docx",
            "resources\\output"
    };
    try {
        Runtime.getRuntime().exec(cmd);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Nothing happens, no errors but no result also

like image 522
Iraklis Bekiaris Avatar asked Dec 07 '25 10:12

Iraklis Bekiaris


1 Answers

Unlike python Java may need some help. Do I guess correctly you are running on Windows?

You invoke the Runtime.exec() method. The method returns a Process instance, and in it's documentation you can read

By default, the created process does not have its own terminal or console. All its standard I/O (i.e. stdin, stdout, stderr) operations will be redirected to the parent process, where they can be accessed via the streams obtained using the methods getOutputStream(), getInputStream(), and getErrorStream(). The parent process uses these streams to feed input to and get output from the process. Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the process may cause the process to block, or even deadlock.

So it is likely your process is started by the OS but gets blocked due to I/O restrictions. Get around that by reading the STDOUT and STDERR streams until your process finishes. One good programming model is visible at https://www.baeldung.com/run-shell-command-in-java

like image 60
Hiran Chaudhuri Avatar answered Dec 10 '25 00:12

Hiran Chaudhuri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!