Running .py file with Java

I am trying to execute a .py file from java code. I move the .py file to the standard directory of my java project, and I invoke 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 the variable path, or the entire path, or "python file.py" runs my code showing a successful total message assembly time of 0 seconds without executing file.py. What is my problem?

+8
java python
source share
3 answers

You can also use this:

 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

+8
source share

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(); 
+4
source share

You can run python script

 Process p = Runtime.getRuntime().exec(PYTHON_ABSOLUTE_PATH, script_path) 

To get the value PYTHON_ABSOLUTE_PATH, just type

 which python2.7 

in the terminal

+1
source share

All Articles