How do I run this python script in java? - java

I want to use this script in my java app: https://github.com/jcapona/amazon-wishlist-scraper.
I've looked around and I tried executing the script like so:
public static void main(String[] args) throws IOException {
String s = null;
Process p = Runtime.getRuntime().exec("python C:\\\\Users\\\\Home\\\\work\\\\test.py");
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
while ((s=stdInput.readLine()) != null) {
System.out.println(s);
}
}
But I am not getting any output. What do I need to be able to run this specific script?

You can use like this :
String command = "python /c start python path\to\script\script.py>";
Process p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
BufferedReader stdErr = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String line;
while ((line = stdInput.readLine()) != null) {
System.out.println(line);
}
stdInput.close();
while ((line = stdErr.readLine()) != null) {
System.out.println(line);
}
stdErr.close();
p.waitFor();
System.out.println("Done.");
p.destroy();
Protip: Always copy your path from the file explorer tab
And since you are getting JSON response try GSON library to parse it.
And if you want to work heavily on python using java, try exploring Jython

Related

Listing virtual disks in Java

Is there a way to list all virtual disks attached using Java?
I've tried using ProccessBuilder to open diskpart and running command and then using InputStreamReader, save lines into an array to later extract vhd name. But after running diskpart command my program freezes.
try {
commands.add("cmd.exe");
commands.add("start");
commands.add("diskpart");
commands.add("list vdisk");
ProcessBuilder builder = new ProcessBuilder(commands);
Process p = builder.start();
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br = new BufferedReader(new InputStreamReader(p.getErrorStream()));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}

Return output of Java Exec when providing array

I'm using java's exec() to run some *nix system commands, specifically a python script, but the problem is more general.
import java.io.*;
public class JRC {
public static void main(String args[]) {
String s[] = {"/bin/bash", "-c",
"source venv/bin/activate;python mergeExcel.py '/home/201811/'"};
try{
Process p = Runtime.getRuntime().exec(s);
}
catch (IOException e) {
System.out.println("exception: ");
e.printStackTrace();
}
}
}
The above code works, in accordance with the extent to which mergeExcel.py works.
However, I can't figure out how to print to stdout from python.
Here's my attempt, which only works if we exec() a simple string such as "ps -ef", rather than the array of strings i'm using.
try {
Process p = Runtime.getRuntime().exec(s);
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
System.exit(0);
}
This actually results in a compilation error of incompatible types, java.lang.String instead of the required java.lang.String[].
How can I can print output from the source venv/.. command and the python command?
Thanks to the commenter, it's trivial to declare some temporary strings to print from stdout and stderr, though perhaps another user has a more elegant solution
try {
Process p = Runtime.getRuntime().exec(s);
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
String stdi;
while ((stdi = stdInput.readLine()) != null) {
System.out.println(stdi);
}
String stderr;
while ((stderr = stdError.readLine()) != null) {
System.out.println(stderr);
}
System.exit(0);
}

Java InputStream to string

in my java program, i am trying to get the InputStream from a process and print it with this piece of code:
try {
Process p = Runtime.getRuntime().exec("cmd /c start dammage\\4.simulation.cmd");
//BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
//StringBuffer sb = new StringBuffer();
//String line;
//while ((line = br.readLine()) != null) {
//sb.append(line).append("\n");
//}
//System.out.println(sb.toString());
String input = IOUtils.toString(p.getErrorStream());
System.out.println(input);
} catch (IOException ex) {
Logger.getLogger(UI.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(this, "Something happened");
}
I tried both ways shown above (commented and uncommented), but none of them prints anything. So i would like to ask what am i doing wrong here?
I appreciate any help.
The buffered reader solution looks fine. You might be looking in the wrong stream. Try getting from both streams.. Like
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
StringBuffer sb = new StringBuffer();
String line;
//Read the output from the command
while ((line = stdInput.readLine()) != null) {
sb.append(line).append("\n");
}
//read any errors from the attempted command
while ((line = stdError.readLine()) != null) {
sb.append(line).append("\n");
}
Are you sure it should print something? Because, the commented code should work just right provided the command executed is returning non-empty input stream. Try replacing the argument of exec to "cmd". And see if it's able to read from the input stream. Do following. On windows machine it should give you welcome message from cmd (the usual welcome message we get after we run start command prompt).
Process p = Runtime.getRuntime().exec("cmd");
About the uncommented code, How IOUtils work? Does it read from the error stream repeatedly. Because, IMO, it's just one time read and not the repetitive one.
Hope I don't confuse.
You should add a p.waitFor(); to give the program time to terminate. Also, verify if you really want to read stdout or stderr
This works for me:
Process p = Runtime.getRuntime().exec("cmd /c java -version");
int ret = p.waitFor();
System.out.println("process terminated with return code: " + ret);
BufferedReader br = new BufferedReader(new InputStreamReader(p.getErrorStream()));
StringBuffer sb = new StringBuffer();
String line;
while((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
System.out.println(sb.toString());

empty ProcessBuilder InputStream

I have some problems using the java ProcessBuilder.
I want to get my gpg keys, so I use the following code:
ProcessBuilder builder = new ProcessBuilder("C:\\[path]\\GnuPG\\pub\\gpg.exe", "--list-keys");
//builder.directory(new File("C:\\[path]\\GnuPG\\pub\\"));
Process process = builder.start();
Scanner s = new Scanner(process.getInputStream()).useDelimiter("\\Z");
System.out.println(s.next());
s.close();
But I always get a NoSuchElementException when executing s.next().
If I use the gpg command "-h", I always get the expected output.
If I change the Constructor call to
new ProcessBuilder("cmd", "/c", "C:\\[path]\\GnuPG\\pub\\gpg.exe", "--list-keys");
it sometimes works. But most times it doesn´t.
WHY? Can anyone help? THANKS!!
Try this-
Test test = new Test();
List<String> commands = new ArrayList<String>();
commands.add("C:\\[path]\\GnuPG\\pub\\gpg.exe");
commands.add("--list-keys");
test.doCommand(commands);
}
public void doCommand(List<String> command)
throws IOException
{
String s = null;
ProcessBuilder pb = new ProcessBuilder(command);
Process process = pb.start();
BufferedReader stdInput = new BufferedReader(new InputStreamReader
(process.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader
(process.getErrorStream()));
StringBuffer start= new StringBuffer();
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null)
{
start.append(s);
System.out.println(s.toString());
}
stdInput.close();
// 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)
{
start.append(s);
System.out.println(s);
}
}

Hibernate-SQLite Dump and Import via Java

How can I make use of Hibernate to perform a backup on my sqlite database? The output should ideally be in the form of an SQL script, similar to the .dump sqlite utility.
Also, to perform a restore of the sql script programmatically as well.
I have found an alternative to do this, and it is by invoking the sqlite3 command line shell via Java. Here's my sample solution
public class Test {
public static void main(String args[]) {
try {
String line;
Process p = Runtime.getRuntime().exec("cmd /c start /b sqlite3 db.sqlite .dump > dump.txt");
BufferedReader bri = new BufferedReader
(new InputStreamReader(p.getInputStream()));
BufferedReader bre = new BufferedReader
(new InputStreamReader(p.getErrorStream()));
while ((line = bri.readLine()) != null) {
System.out.println(line);
}
bri.close();
while ((line = bre.readLine()) != null) {
System.out.println(line);
}
bre.close();
p.waitFor();
System.out.println("Done.");
}
catch (Exception err) {
err.printStackTrace();
}
}
}
To my knowledge there is no mechanism in Java to do an SQL dump. But you could create a program to do it quite easily by:
Iterating through a list of your entities - built up using reflection perhaps.
Get you list of column names using JDBC direct (cant really do it with hibernate).
Then creating a select query you pass the Entity name into as a parameter.
Iterate over the result set and push the data via a formatted string to a file.
You can of course add in a DROP IF EXISTS before each CREATE if required.
For Unix Flavor cmd not working so used this for ubuntu.
try
{
String line;
Runtime rt = Runtime.getRuntime();
Process p = rt.exec(new String[]{"/bin/sh", "-c", "sqlite3 /home/ubuntu/test.sqlite .dump > /home/ubuntu/output.sql"});
BufferedReader bri = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader bre = new BufferedReader(new InputStreamReader(p.getErrorStream()));
while ((line = bri.readLine()) != null) {
System.out.println(line);
}
bri.close();
while ((line = bre.readLine()) != null) {
System.out.println(line);
}
bre.close();
p.waitFor();
System.out.println("Done.");
} catch (Exception err) {
err.printStackTrace();
}

Categories