Bramat
Bramat

Reputation: 997

Run java code in python - with input/output

I have a python script - and I need to run a .jar from it.

What I need is to send an array as input to the Java code, and I want to receive an array as output.

How can I do that? Thank you all in advanced!

Upvotes: 0

Views: 4999

Answers (2)

osanger
osanger

Reputation: 2352

Python 2.7

#!/usr/bin/env python2.7

import os
import subprocess

# Make a copy of the environment    
env = dict(os.environ)
env['JAVA_OPTS'] = 'foo'
subprocess.call(['java', '-jar', 'temp.jar'], env=env)

Python 3

#!/usr/bin/env python3
from subprocess import check_output

result = check_output(['java', '-jar', 'temp.jar'], input=b'foo')

Upvotes: 0

Roelant
Roelant

Reputation: 5119

Since a while, the os module is depreciated (but can still be used) and subprocess is the suggested method.

import subprocess 
result = subprocess.check_output(["java -jar example.jar", str(your_array)], shell=True)

You can also use Popen, see for example python getoutput() equivalent in subprocess

Upvotes: 1

Related Questions