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 OverflowYou 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
If you are using Linux you can use the os.system command:
os.system("your_java_file > out_put_file")
This command will execute the file and print the output to the out_out_file Then you can read the output file.
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!
I would use subprocess this way:
import subprocess
subprocess.call(['java', '-jar', 'Blender.jar'])
But, if you have a properly configured /proc/sys/fs/binfmt_misc/jar you should be able to run the jar directly, as you wrote.
So, which is exactly the error you are getting? Please post somewhere all the output you are getting from the failed execution.
This always works for me:
from subprocess import *
def jarWrapper(*args):
process = Popen(['java', '-jar']+list(args), stdout=PIPE, stderr=PIPE)
ret = []
while process.poll() is None:
line = process.stdout.readline()
if line != '' and line.endswith('\n'):
ret.append(line[:-1])
stdout, stderr = process.communicate()
ret += stdout.split('\n')
if stderr != '':
ret += stderr.split('\n')
ret.remove('')
return ret
args = ['myJarFile.jar', 'arg1', 'arg2', 'argN'] # Any number of args to be passed to the jar file
result = jarWrapper(*args)
print result
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
Here your first problem is with your java version with which you have compiled the code and java version with which you are running the code.
For example, if you have compiled the code with java version 8 and you are running the java application with java version 7 or 6 (lower than compiled one) you will get a Unsupported major.minor version 52.0 error. Hence compile the code with a lower or same version than your server one.
Check the version in your server : java --version
Check the version in your development tool with which you have compiled the code
In the below code, provide full path to your jar file as well.
os.system("java -jar \fullpath\PGPEncryption.jar BC.csv.pgp X.csv <password>")
If you want to use modules in JAR file in python code, the you need to run that py file using JYTHON.
java -jar jython.jar demo.py
Jython download
Check here for tutorial
Subprocess with Popen
import subprocess
x = subprocess.Popen("java -jar PGPEncryption.jar BC.csv.pgp X.csv <password>", stderr=subprocess.PIPE, stdout=subprocess.PIPE)
out,err = x.communicate()
print "Error is - ",err
print "Output is -",out
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/
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.