简体   繁体   中英

Send commands to Running Python Script

I am working on a small java app that needs to start a python script and interact with it. The python script is to run in the background and wait for commands. After each command I expect a response which will be forwarded back to the java app.

I have used the examples here and here to open the python script.

My question is how do I, without re-running the python script hook into it and run my commands?

public void startProcess()
{
    try {
        p = Runtime.getRuntime().exec("python " + scriptPath);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public String executeCommand(String cmd)
{
    String consoleResponse = "";

    try {
        // how do I perform something similar to p.exec(cmd)

        BufferedReader stdInput = new BufferedReader(new
                 InputStreamReader(p.getInputStream()));

        BufferedReader stdError = new BufferedReader(new
                 InputStreamReader(p.getErrorStream()));

        // read the output from the command
        System.out.println("Here is the standard output of the command:\n");
        while ((consoleResponse += stdInput.readLine()) != null) {
        }

        // read any errors from the attempted command
        System.out.println("Here is the standard error of the command (if any):\n");
        while ((consoleResponse = stdError.readLine()) != null) {
        }

    } catch (IOException e) {
        e.printStackTrace();
    }

    return consoleResponse;
}

EDIT: The python script is for BACpypes. The script does 3 things. WhoIs: gets a list of all devices connected over bacnet ReadHexFile: reads in a text file to be sent to all devices on the network SendFile: sends the file to all devices.

I am not experienced with python and feel it would be simpler to keep all this data in one script.

I suppose one option is to break each command into its own script and pass the data to the java application.

how do I, without re-running the python script hook into it and run my commands?

You would need to make the single Python script keep listening for the new input or requests (back and forth communication), but I think that would be a slight pain and also makes your python script less clear than the standard input -> process -> output flow.

What is the reason for avoiding running multiple Python scripts?


To write input to your scripts stdin, do something like this:

public static void main(String[] args) throws IOException, InterruptedException {
    ProcessBuilder pb = new ProcessBuilder("python", "path\\to\\script.py");
    Process pr = pb.start();

    try (BufferedWriter writerToProc = new BufferedWriter(
            new OutputStreamWriter(pr.getOutputStream()));
            BufferedReader readerOfProc = new BufferedReader(
                    new InputStreamReader(pr.getInputStream()));
            BufferedReader errorsOfProc = new BufferedReader(
                    new InputStreamReader(pr.getErrorStream()))) {

        writerToProc.write("WhoIs\n");
        writerToProc.write("ReadHexFile\n"); // is this the syntax?
        writerToProc.write("SendFile 'path\to\file.txt'\n");
        writerToProc.flush();

        StringBuilder procOutput = new StringBuilder();
        boolean gaveUp = false;
        long waitTime = 10 * 1_000; // 10 seconds
        long lastRead = System.currentTimeMillis();
        for(;;) {
             final long currTime = System.currentTimeMillis();
             final int available = readerOfProc.available();
             if(available > 0){
                 // TODO read the available bytes without blocking
                 byte[] bytes = new byte[available];
                 readerOfProc.read(bytes);
                 procOutput.append(new String(bytes));

                 // maybe check this input for an EOF code
                 // your python task should write EOF when it has finished
                 lastRead = currTime;
             } else if((currTime - lastRead) > waitTime){
                 gaveUp = true;
                 break;
             }
        }


        // readerOfProc.lines().forEach((l) -> System.out.println(l));
        // errorsOfProc.lines().forEach((l) -> System.out.println(l));
    }
}

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