简体   繁体   中英

Running python script, as exe, with parameters, from Java

I have found some tips on how to do that, but combining them together does not work, so i am asking for help.

I have a script in python, which gets it's variables from parameters(arguments?)(sys.argv). I have used PyInstaller to create an exe.

Now i need to open this file, with parameters, from java.

The problem is, i got the error: Failed to execute script [ScriptName].

This is my code from java:

try {
    ProcessBuilder process = new ProcessBuilder(Location, arg1, arg2, arg3, arg4,
                                                arg5, arg6, arg7, arg8, arg9,
                                                arg10, arg11, arg12, arg13, arg14);
    Process proc = process.start();
    proc.waitFor();
} catch (IOException | InterruptedException e) {
    //logging the result
    e.printStackTrace();
}

And this is my code in python:

arg1 = sys.argv[2]
arg2 = sys.argv[3]
arg3 = sys.argv[4]
arg4 = sys.argv[5]
arg5 = sys.argv[6]
(...)

I have tried different 'argv positions' (ie arg1 = sys.argv[1] etc.), but nothing works.

Thanks in advance for any help.

You can try to compose a call String with all your arguments like this (you should use a StringBuilder or something similar for tidy code):

String call = "python yourscript.py argument1 argument2 argument3";
Process p = Runtime.getRuntime().exec(call);

So far, this has always worked for me, without even needing an .exe. Also, you should be able to run an .exe the exact same way.

None of the things mentioned have worked, i have decided to do it by txt file (writing txt in java and reading it in python).

I think that the best option would be to do pass the data by database, but in that case it was not an option :(

BTW. i also have tried getting values by argparse instead of sys.arg, but i think the problem was in java (The script was not even executed).

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