Running a .Py File from Java

Running a .py file from Java

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

How to Run a Python file from Java using an Absolute Path?

Try using something more like...

Runtime.getRuntime().exec("python "+cmd + py + ".py");

Instead. Each exec is it's own process and multiple exec has no relationship to each other...

You should also consider using ProcessBuilder instead, as this provides you with a great level of configurability, for example, you can change the execution path context...

ProcessBuilder pb = new ProcessBuilder("python", py + ".py");
pb.directory(new File(cmd));
pb.redirectError();
//...
Process p = pb.start();

Also, beware, that Python has an issue with it's output stream, which may prevent Java from reading it until it's completely finished if at all...

For more details, take a look at Java: is there a way to run a system command and print the output during execution?

Also, make sure python is within the shell's search path, otherwise you will need to specify the full path to the command as well

Trying to call python file from java

Use BufferedReader to show your output.

import java.io.*;
class Test {
public static void main(String args[]) {
try {
Process p = Runtime.getRuntime().exec(
"python Test.py ");
BufferedReader in = new BufferedReader(new InputStreamReader(
p.getInputStream()));
System.out.println(in.readLine());
} catch (Exception e) {
}
}

}

and my python file is Test.py

print "Hello World Python.";

How to run python script from java without storing the script in a .py file?

You can also probably run the script like this :

String script = "your script from server";
ProcessBuilder pb = new ProcessBuilder("python3", "-c", script);
pb.start();

In a shell the python -c allow you to run a script that you write in the shell.

How to execute Python script from Java (via command line)?

You cannot use the PIPE inside the Runtime.getRuntime().exec() as you do in your example. PIPE is part of the shell.

You could do either

  • Put your command to a shell script and execute that shell script with .exec() or
  • You can do something similar to the following

    String[] cmd = {
    "/bin/bash",
    "-c",
    "echo password | python script.py '" + packet.toString() + "'"
    };
    Runtime.getRuntime().exec(cmd);

Run Python script through Java with importing just once

You could communicate between java and Python with pipes.

You run your Python as you do now (without command line args)

Python script

you write an infinite loop in python that will


  1. read data from the
    standard input (it will be your arg for the function)

  2. You call your function

  3. you write the answer to the standard output

Java

  1. Write a method for sending args to python

  2. write to the pipe the arg of your function

  3. read the answer from the pipe

You're done.

Here is some snippet

Here how you create your tube

        Process p = Runtime.getRuntime().exec(commande);
BufferedReader output = getOutput(p); //from python to java
BufferedReader error = getError(p); //from python to java
PrintWriter input = getInput(p); //from java to python

private static BufferedReader getOutput(Process p) {
return new BufferedReader(new InputStreamReader(p.getInputStream()));
}
private static BufferedReader getError(Process p) {
return new BufferedReader(new InputStreamReader(p.getErrorStream()));
}
private static PrintWriter getInput(Process p){
return new PrintWriter (new OutputStreamWriter(p.getOutputStream()));
}

Running python script from jar file

The problem had multiple layers and solutions:
1. I didn't put .py file in jar build config
2. After putting it I always got an exception that it is null because of a typo in code
3. After trying many ways to run it this one worked Cannot run python script from java jar
. The important thing is to check if you added py file to the build config and to run it in a proper way since python cannot runt files from the zip and compressed states.

I can't run a python script from java and I think it's because the script does not have execute permissions

Use complete python executable path instead of "py". It executes the file with just read permissions.

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

public class Sample {

public static void main(String[] args) throws Exception {
try {
Process p = Runtime.getRuntime().exec("C:/Windows/py myScript.py");
String cmdOutput = null;
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
// read the output from the command
while ((cmdOutput = stdInput.readLine()) != null) {
System.out.println(cmdOutput);
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}

myScript.py

print("This line will be printed.")

Output:

C:\Users\Administrator\Documents\demo>javac Sample.java

C:\Users\Administrator\Documents\demo>java Sample
This line will be printed.


Related Topics



Leave a reply



Submit