t0x13
t0x13

Reputation: 359

Python - Passing data to a jar file as input stream

I have a jar file that I can send data to for processing, the data is in json format. data_path is a path to a file that has the data. Below works great.. However the data I have is not going to be a file, but in a variable. Below command does not work with a variable, it tries to read the data passed as a literal directory path to file.. Would it be a different bash command ? or something I can do with the subprocess module? Thanks!

import subprocess as sub

cmd = "java -jar %s < %s" % (jar_path, data_path)
# send data in a var
# cmd = "java -jar %s < %s" % (jar_path, data)
proc = sub.Popen(cmd, stdin=sub.PIPE, stdout=sub.PIPE, shell=True)
(out, err) = proc.communicate()

Upvotes: 0

Views: 1057

Answers (1)

jdi
jdi

Reputation: 92569

You can write it to a temporary file and pass that:

import tempfile

with tempfile.NamedTemporaryFile() as f:
    f.write(data)
    f.flush()
    cmd = "java -jar %s < %s" % (jar_path, f.name)
    ...

The temp file will delete itself when the context ends.

@FedorGogolev had deleted answers going for a Popen stdin approach that weren't quite working for your specific needs. But it was a good approach so I credit him, and thought I would add the working version of what he was going for...

import tempfile

with tempfile.TemporaryFile() as f:
    f.write(data)
    f.flush()
    f.seek(0)
    cmd = "java -jar %s" % jar_path
    p = subprocess.Popen(cmd, shell=True, stdin=f, stdout=subprocess.PIPE)
    ...

If you are passing the file object as the stdin arg you have to make sure to seek it to 0 position first.

Upvotes: 1

Related Questions