I am trying to execute a .py file from java code. I move the .py file in the default dir of my java project and I call it using the following code:
String cmd = "python/";
String py = "file";
String run = "python " +cmd+ py + ".py";
System.out.println(run);
//Runtime.getRuntime().exec(run);
Process p = Runtime.getRuntime().exec("python file.py");
Either using variable run, or the whole path or "python file.py" my code is running showing the message build successful total time 0 seconds without execute the file.py. What is my problem here?
First, we begin by setting up a ScriptContext which contains a StringWriter. This will be used to store the output from the script we want to invoke. We then use the getEngineByName method of the ScriptEngineManager class to look up and create a ScriptEngine for a given short name.
javabridge. CPython, that can be used to execute Python code. The class can be used within Java code called from the Python interpreter or it can be used within Java to run Python embedded in Java. The CPython class binds the Python interpreter to the JVM and provides the ability to execute Python scripts.
To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World!
The seamless interaction between Python and Java allows developers to freely mix the two languages both during development and in shipping products.
You can use like this also:
String command = "python /c start python path\to\script\script.py";
Process p = Runtime.getRuntime().exec(command + param );
or
String prg = "import sys";
BufferedWriter out = new BufferedWriter(new FileWriter("path/a.py"));
out.write(prg);
out.close();
Process p = Runtime.getRuntime().exec("python path/a.py");
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String ret = in.readLine();
System.out.println("value is : "+ret);
Run Python script from Java
I believe we can use ProcessBuilder
Runtime.getRuntime().exec("python "+cmd + py + ".py");
.....
//since exec has its own process we can use that
ProcessBuilder builder = new ProcessBuilder("python", py + ".py");
builder.directory(new File(cmd));
builder.redirectError();
....
Process newProcess = builder.start();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With