chase chase - 1 year ago 83
Java Question

terminal output to variable (from java to python) - Best coding practices for placing output into RAM instead of writing files

I am wondering what the best course of action would be in order to get a java ".jar" file output into a python variable.

For example, let's say a user has a complicated java package (that perhaps the user didn't write and doesn't understand) which they can run in the command window / terminal with

java -jar FileProcessor.jar -i "input.txt" -o "output.txt"

Is there a manner to call this in python and get the "output.txt" in a variable, similar to this method:

proc = subprocess.Popen(['java', '-jar', 'FileProcessor.jar', '-i', 'sample.txt', '-o'], stdout=subprocess.PIPE)
py_out =

The problem is clearly that the java file looks for the output file

Obviously I am open to other ideas, but as I understand my main options are:

  1. subprocess
    ? using stdout to log the variable

  2. Write a wrapper of the java package

Is there a better way to achieve this? The first method doesn't appear to be working as easily as many examples would show and I have no idea how difficult it would be to write a wrapper around a java package as I have never done so.

Answer Source

if your program FileProcessor.jar doesn't have a special case to output to standard output, there's nothing much you can do (but write to a temporary file and read it again, but that's cheating :).

Most nice commands (Unix commands for instance) either dump data to stdout when the -o option is omitted, or when -o option has - value (dash).

Best option is to modify your java program to behave like that.

An alternative on Unix/Linux if you cannot modify your program:

  • get current tty with tty command. Ex: /dev/pts/2
  • pass that to your program
  • read standard output
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download