You can read the output through pipe:

>>> from subprocess import Popen, PIPE, STDOUT
>>> p = Popen(['java', '-jar', './GET_DB_DATA.jar'], stdout=PIPE, stderr=STDOUT)
>>> for line in p.stdout:
    print line

As regards passing string to stdin, you can achieve it this way:

>>> p = Popen(['cat'], stdin=PIPE, stdout=PIPE, stderr=STDOUT)
>>> stdout, stderr = p.communicate(input='passed_string')
>>> print stdout
passed_string
Answer from ovgolovin on Stack Overflow
🌐
Reddit
reddit.com › r/learnpython › how do i call a jar file in python and execute code based off of the output of the jar?
r/learnpython on Reddit: How do I call a jar file in python AND execute code based off of the output of the jar?
April 22, 2018 -

Hi, I've got a .jar file that outputs a lot of text continuously. I've been using the following code to open the .jar in python.

import subprocess subprocess.call(['java', '-jar', 'prox.jar'])

I can see that all is working because I can see the output text in the IDLE, but I'm stuck on how to execute code based on the continuous output. So like...

if "test" in live_output_of_Jar: ... if "othertext" in... you get the idea.

Thanks!

🌐
Raspberry Pi Forums
forums.raspberrypi.com › board index › programming › python
.jar output to python variable to results in no output - Raspberry Pi Forums
import smtplib import subprocess s = smtplib.SMTP('smtp.gmail.com', 587) s.starttls() s.ehlo() username='[email protected]' password='password' s.login(username,password) replyto='[email protected]' sendto=['[email protected]'] sendtoShow='[email protected]' subject='Example Subject' content=subprocess.run(['java', '-jar', 'Example.jar'], stdout=subprocess.PIPE) mailtext='From: '+replyto+'\nTo: '+sendtoShow+'\n' mailtext=mailtext+'Subject:'+subject+'\n'+content.stdout.decode("utf-8") s.sendmail(replyto, sendto, mailtext) rslt=s.quit() print('Sendmail result=' + str(rslt[1])) ... You should use subprocess.Popen to run the Java program. Then subprocess.communicate() will get the subprocess.stdout stuff for you. Example here: https://kite.com/python/docs/subprocess ...
🌐
Data Science Learner
datasciencelearner.com › python › how-to-call-jar-file-using-python
How to Call Jar File Using Python? - Python Tutorial Data Science Learner
October 27, 2022 - This article " How to call jar file using Python " will brief you on two different ways in Python to call jar externally (os.system and subprocess.call) .
🌐
Reddit
reddit.com › r/learnpython › running a .jar file through a python script
r/learnpython on Reddit: running a .jar file through a python script
May 25, 2013 -

This is what I am using right now

os.system("java -jar FULL_PATH\RR.jar")

A command prompt console window pops up for an instance and all i can read is 4 lines reading success followed by some other text.

Any help will be welcome

🌐
IQCode
iqcode.com › code › shell › python-run-java-jar
python run java jar Code Example
October 27, 2021 - import subprocess subprocess.call(['java', '-jar', 'jarfile.jar'])
🌐
Python Forum
python-forum.io › thread-34418.html
printing out the contents aftre subprocess.call()
I am facing a scenario where in I need to execute a jar based on user parameters. I have replicated the scenario here as below : import subprocess a = input('Enter either 2 or 3:') value = int(a) if a == 2: p1 = subprocess.run(['java', '-jar',...
Find elsewhere
🌐
CodingTechRoom
codingtechroom.com › question › execute-java-from-python
How to Execute Java Programs from Python Code? - CodingTechRoom
import subprocess result = subprocess.run(['java', '-jar', 'YourJavaProgram.jar'], capture_output=True, text=True) print(result.stdout) Executing Java programs from Python can be achieved through various methods, but the most common approach involves using the `subprocess` module.
🌐
CodingTechRoom
codingtechroom.com › question › executing-jar-files-from-python-a-complete-guide
How to Execute a JAR File Using Python Script - CodingTechRoom
import subprocess # Define the path to the jar file jar_path = 'path/to/your/Blender.jar' # Execute the jar file using subprocess subprocess.run(['java', '-jar', jar_path]) Incorrect path to the JAR file. Java is not installed or not added to the system PATH. Using older Python versions that may have compatibility issues. Ensure that the path to the JAR file is correct and includes the file extension.
Top answer
1 of 4
2
You can use Java Runtime.exec() to run python script, As an example first create a python script file using shebang and then set it executable.#!/usr/bin/python import sys print ('Number of Arguments:', len(sys.argv), 'arguments.') print ('Argument List:', str(sys.argv)) print('This is Python Code') print('Executing Python') print('From Java')if you save the above file as script_python and then set the execution permissions usingchmod 777 script_pythonThen you can call this script from Java Runtime.exec() like belowimport java.io.*; import java.nio.charset.StandardCharsets; public class ScriptPython { Process mProcess; public void runScript(){ Process process; try{ process = Runtime.getRuntime().exec(new String[]{"script_python","arg1","arg2"}); mProcess = process; }catch(Exception e) { System.out.println("Exception Raised" + e.toString()); } InputStream stdout = mProcess.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(stdout,StandardCharsets.UTF_8)); String line; try{ while((line = reader.readLine()) != null){ System.out.println("stdout: "+ line); } }catch(IOException e){ System.out.println("Exception in reading output"+ e.toString()); } } } class Solution { public static void main(String[] args){ ScriptPython scriptPython = new ScriptPython(); scriptPython.runScript(); } }Hope this helps and if not then its recommended to join our Java training class and learn about Java in detail.
2 of 4
0
There are three ways to get this done:runtime approachprocess approachjython approachHave a look at this blog for detailed explanation with example.
Top answer
1 of 10
81

Not sure if I understand your question correctly, but provided that you can call the Python executable from the console and just want to capture its output in Java, you can use the exec() method in the Java Runtime class.

Process p = Runtime.getRuntime().exec("python yourapp.py");

You can read up on how to actually read the output from this resource: http://www.devdaily.com/java/edu/pj/pj010016 import java.io.*;

public class JavaRunCommand {

    public static void main(String args[]) {

        String s = null;

        try {
            
        // run the Unix "ps -ef" command
            // using the Runtime exec method:
            Process p = Runtime.getRuntime().exec("ps -ef");
            
            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 ((s = stdInput.readLine()) != null) {
                System.out.println(s);
            }
            
            // read any errors from the attempted command
            System.out.println("Here is the standard error of the command (if any):\n");
            while ((s = stdError.readLine()) != null) {
                System.out.println(s);
            }
            
            System.exit(0);
        }
        catch (IOException e) {
            System.out.println("exception happened - here's what I know: ");
            e.printStackTrace();
            System.exit(-1);
        }
    }
}

There is also an Apache library (the Apache exec project) that can help you with this. You can read more about it here:

http://www.devdaily.com/java/java-exec-processbuilder-process-1

http://commons.apache.org/exec/

2 of 10
36

You can include the Jython library in your Java Project. You can download the source code from the Jython project itself.

Jython does offers support for JSR-223 which basically lets you run a Python script from Java.

You can use a ScriptContext to configure where you want to send your output of the execution.

For instance, let's suppose you have the following Python script in a file named numbers.py:

for i in range(1,10):
    print(i)

So, you can run it from Java as follows:

public static void main(String[] args) throws ScriptException, IOException {

    StringWriter writer = new StringWriter(); //ouput will be stored here
    
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptContext context = new SimpleScriptContext();
    
    context.setWriter(writer); //configures output redirection
    ScriptEngine engine = manager.getEngineByName("python");
    engine.eval(new FileReader("numbers.py"), context);
    System.out.println(writer.toString()); 
}

And the output will be:

1
2
3
4
5
6
7
8
9

As long as your Python script is compatible with Python 2.5 you will not have any problems running this with Jython.

🌐
Reddit
reddit.com › r/learnpython › difficulty executing a .jar file using python
r/learnpython on Reddit: Difficulty executing a .jar file using Python
May 29, 2016 - I tried running it directly and with a batch file and both work fine. EDIT: I found out how to print the traceback, I don't know what it means though: Traceback (most recent call last): File "C:\Users\ali\Documents\Java Stuff\RedditFitnessCalc\out\artifacts\RedditFitnessCalc_jar\pythonBotScript.py", line 6, in <module> p = subprocess.check_output(['java', '-jar', 'RedditFitnessCalc.jar']) File "C:\Program Files (x86)\Python 3\lib\subprocess.py", line 620, in check_output raise CalledProcessError(retcode, process.args, output=output) subprocess.CalledProcessError: Command '['java', '-jar', 'RedditFitnessCalc.jar']' returned non-zero exit status 2 ·