Invoking an "interactive" Perl script from Java

I want to call an "interactive" Perl script from a Java program. Just for clarity, the other way around (from Perl to Java) is not suitable for me.

The script is interactive in the sense that it requires a small configuration dialog with the user. For example, a script call in cmd.exe will lead to a dialog, for example:

Do you want to overwrite the old settings? [yes, no (default = no)]

and the user must choose between spelling yes, no or nothing on the command line. And depending on the user's choice, another message will appear: "Do you want ....", and the user will respond, etc. Etc. I think you got the image.

My question is: how can I have the same dialog with the user when the script is called in a Java program? I mean, how can I capture script questions to the user, show them to the user, and then send the user's response (received in the Java program) to the script?

Simple Runtime.getRuntime (). exec () in this case does not work.

I hope that I have clearly stated the question.

Thank you for your help!

+2
source share
3 answers

You must use the getInputStream / getOutputStream methods to access stdin and stdout perl stript. You can read and write to these threads to simulate user behavior.

OutputStream stdin = null; InputStream stderr = null; InputStream stdout = null; Process process = Runtime.getRuntime ().exec ("..."); stdin = process.getOutputStream (); stderr = process.getErrorStream (); stdout = process.getInputStream (); // "write" the parms into stdin String line = "data\n"; stdin.write(line.getBytes()); stdin.flush(); stdin.close(); // clean up if any output in stdout BufferedReader brCleanUp = new BufferedReader (new InputStreamReader (stdout)); while ((line = brCleanUp.readLine ()) != null) { //System.out.println ("[Stdout] " + line); } brCleanUp.close(); // clean up if any output in stderr brCleanUp = new BufferedReader (new InputStreamReader (stderr)); while ((line = brCleanUp.readLine ()) != null) { //System.out.println ("[Stderr] " + line); } brCleanUp.close(); 
+4
source

This is a job for Expect . In Java: ExpectJ , expect4j

0
source

If (1) your call from Java to Perl and (2) you do not parse the Perl script itself, why not use JOptionPane.showConfirmDialog () from the Java code? There should not be a big deal, if yes / no - all that you get from the script. Everything that you print for display to the user can be included in this confirmation dialog as plain ASCII text.

-1
source

Source: https://habr.com/ru/post/911948/


All Articles