Trying to retrieve python version from java - java

I'm trying to retrieve the version of python form java using ProcessBuilder.
The command i'm using is:
{process = new ProcessBuilder("C:\\Python27\\python.exe", "-V")}
This command does not return anything.
I'm almost sure this is the correct syntax to retrieve the python version,
{process = new ProcessBuilder("C:\\Python27\\python.exe", "-h")}
returns the python help as expected, but python -V does not return the python version.
package com.x.x.precheck.python;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
public class Test {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Process process = null;
try {
process = new ProcessBuilder("C:\\Python27\\python.exe", "-V")
.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
System.out.printf("Output of running %s is:", Arrays.toString(args));
try {
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

It's because, strangely enough, the python2.7 version is displayed in stderr. in python version 3.4 this behaviour will change see http://bugs.python.org/issue18338
so instead of
InputStream is = process.getInputStream();
you should call
InputStream stderr = process.getErrorStream ();

I tested your code with other programs.It all works fine.for example i gave octave instead of the python and It printed out.Its weird.

Related

Run python script in Java : Why do I get null output?

I'm trying to run a python script in Java. python script converts speech to text. But, after executing it in java, I get null output.
The python script does not have any error and works fine as I run it in the terminal.
I tried "Thread.sleep()" in order to wait for process but It did not help.
"SampleHandler" is my java class name.
Java:
try {
java.net.URL location = SampleHandler.class.getProtectionDomain().getCodeSource().getLocation();
Process p = Runtime.getRuntime().exec(location.getFile() + "resources/speech_to_text.py");
Thread.sleep(8000);
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String ret = "";
ret = in.readLine();
System.out.println(ret);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Python :
import os
import io
from google.cloud import speech
from google.cloud.speech import enums
from google.cloud.speech import types
os.environ["GOOGLE_APPLICATION_CREDENTIALS"]="key.json"
client = speech.SpeechClient()
file_name = os.path.join('audio.wav')
with io.open(file_name, 'rb') as audio_file:
content = audio_file.read()
audio = types.RecognitionAudio(content=content)
config = types.RecognitionConfig(
encoding=enums.RecognitionConfig.AudioEncoding.LINEAR16,
sample_rate_hertz=44100,
audio_channel_count=2,
language_code='en-US')
response = client.recognize(config, audio)
for result in response.results:
print(format(result.alternatives[0].transcript))

How to read adb response from jar?

I am trying to batch some apps installations and I want to do it app by app.
I am trying to get the adb command response into my java program but I don't manage to understand why I don't get anything from an InputStream!
Here is my test code:
import java.io.IOException;
import java.io.InputStream;
public class main_adbStreamTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Process pro = Runtime.getRuntime().exec("platform-tools\\adb.exe -s " + args[0] + ":5555 install -r " + args[1]); // + " >> " + SBCWLogger.getFileHandlerName()
//add installation verification
InputStream is = pro.getInputStream();
int i = 0;
while( (i = is.read() ) != -1) {
System.out.print((char)i);
}
//verification done
} catch (IOException e) {
e.printStackTrace();
}
}
}
I found this answer which is not working, and I do not manage to use pro.getInputStream() properly either.
I also tried most of the answers from here but none of those I tested worked. I successfully read the errors when I don't connect or when the install fails, but not the informational messages as Success at the end of an install. And that is what I want.
EDIT: the code below is working thanks to Onix' answer.
import java.io.IOException;
import java.io.InputStream;
public class main_adbStreamTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Process pro = new ProcessBuilder("platform-tools\\adb.exe", "-s",args[0], "install", "-r", args[1]).start();
//add installation verification
InputStream is = pro.getInputStream();
int i = 0;
while( (i = is.read() ) != -1) {
System.out.print((char)i);
}
//verification done
} catch (IOException e) {
e.printStackTrace();
}
}
}
And to get the famous Success, just write the stream to a file and read the last row.
Try this
Process process = new ProcessBuilder("Full path to adb", "-s", args[0], "install", "-r", args[1]).start();
InputStream is = process.getInputStream();

Running a shell script interactively from a Java class in Linux machine

I have a simple shell script which prints "Hello world", asks for a number from user and prints that number.
I am trying to run this script from a Java class in linux machine using runtime and process.
However, when I run this Java class in linux machine from commandline using java command, it prints the first 2 lines and hangs at the point of taking input from user. I am not able to pass any input to the script.
Kindly let know how I can run the script interactively via java. Below is my script and java class file:
sample.sh
#!/bin/sh
echo "Hello world"
echo "Enter any number"
read response
echo "The number you entered is: $response"
ExecuteScript.java
package com.scripting;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
public class ExecuteScript {
public static void main(String args[]) {
System.out.println("Java program ran!!");
String[] cmdScript = new String[]{"/bin/bash", "/root/sample.sh"};
Process procScript = null;
try {
procScript = Runtime.getRuntime().exec(cmdScript);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InputStream ip = procScript.getInputStream();
OutputStream op = procScript.getOutputStream();
BufferedReader reader = new BufferedReader(new
InputStreamReader(ip));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(op));
BufferedReader consoleReader =
new BufferedReader(new InputStreamReader(System.in));
try {
while(reader.readLine() != null) {
if(!reader.ready()) {
String input = consoleReader.readLine();
writer.write(input);
writer.flush();
}else {
System.out.println(reader.readLine());
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Run python file for AWS CloudFormation using JAVA

I want to run a python file that can run AWS CloudFormation template using JAVA.
I am passing python file in JAVA code.
When I run the JAVA code it pauses at the following state:
compile-single:
run-single:
If i run the Python file from terminal it works perfectly.
Java Code:
private void RunPythonActionPerformed(java.awt.event.ActionEvent evt) {
String pythonScriptPath = "path to python file";
String[] cmd = new String[2];
cmd[0] = "python"; // check version of installed python: python -V
cmd[1] = pythonScriptPath;
// create runtime to execute external command
Runtime rt = Runtime.getRuntime();
Process pr = null;
try {
pr = rt.exec(cmd);
// retrieve output from python script
} catch (IOException ex) {
Logger.getLogger(Page2.class.getName()).log(Level.SEVERE, null, ex);
}
BufferedReader bfr = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line = "";
try {
while((line = bfr.readLine()) != null) {
// display each output line form python script
System.out.println(line);
}
// TODO add your handling code here:
} catch (IOException ex) {
Logger.getLogger(Page2.class.getName()).log(Level.SEVERE, null, ex);
}
}
Provide path to your source file at <complete path to your python source file>
Copying working code for you. For me output is Python 3.6.5
package com.samples;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ProcessBuilderSample {
public static void main(String [] args) throws IOException {
RunPythonActionPerformed();
}
private static void RunPythonActionPerformed() throws IOException {
String pythonScriptPath = "python -V";
Process p = Runtime.getRuntime().exec(pythonScriptPath);
BufferedReader bfr = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
try {
while((line = bfr.readLine()) != null) {
// display each output line form python script
System.out.println(line);
}
// TODO add your handling code here:
} catch (IOException ex) {
}
}
}

Executing imagemagick commands with java gives no output

I am writing a java aplication that edits images using imagemagick commands;
However, the comands do not work and I am getting no output from them;
Actually, the comand identify is not recognized and I get CreateProcess error=2;
This seems odd, because the imagemagick instalation folder is included in my Path variable.
Here's my code:
public class Test {
public static void main(String argv[]) {
Runtime ru = Runtime.getRuntime();
Process p = null;
try {
//I've added this as a bouns, this should not be neccessary(methinks)
String[] s = {"C:\\Program Files\\ImageMagick-6.8.6-Q16"};
String[] cmd = {"convert", "acc-logo.jpg","-flip", "edited.jpg"};
p = ru.exec(cmd,s);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedReader ina = new BufferedReader(new InputStreamReader(
p.getInputStream()));
String line = null;
try {
while ((line = ina.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You have a space in the path to the executable, and the Runtime.exec() call is having problems with it. Use ProcessBuilder instead; it handles spaces in arguments much more easily.

Categories