Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running a .py file from Java

Tags:

java

python

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?

like image 731
Jose Ramon Avatar asked Dec 03 '14 08:12

Jose Ramon


People also ask

How do I run a Python script from Java?

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.

Can we run Python script from Java?

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.

How do I run a .PY file?

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!

Can Java and Python work together?

The seamless interaction between Python and Java allows developers to freely mix the two languages both during development and in shipping products.


2 Answers

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

like image 189
Prateek Avatar answered Sep 20 '22 20:09

Prateek


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();
like image 38
Maddy Avatar answered Sep 19 '22 20:09

Maddy