How do I execute shell script file with an input parameter like "./flows.sh suspend" and print the the result to a file using java in linux?
This is a simple code to execute the shell script and read its output:
import java.io.*;
public class Test {
public static void main(String[] args) throws Exception {
String[] command = { "./flows.sh", "suspend" };
Process process = Runtime.getRuntime().exec(command);
BufferedReader reader = new BufferedReader(new InputStreamReader(
process.getInputStream()));
String s;
while ((s = reader.readLine()) != null) {
System.out.println("Script output: " + s); // Replace this line with the code to print the result to file
}
}
}
To print it to a file, just replace the System.out.println for the code to write into a file
You can use the JSCH API:
http://www.jcraft.com/jsch/examples/Shell.java.html
http://www.jcraft.com/jsch/examples/Exec.java.html
Bye!
Related
I used the following code to execute simple OS command on Windows:
public class Ping {
public static void main(String[] args) throws IOException {
String command = "ping google.com";
Process process = Runtime.getRuntime().exec(command);
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
System.out.println();
System.out.println("Finished");
How to modify the code to insert multiple commands instead of one, so let us say I want to ping google.com, and then ping yahoo.com after that.
I tried to create array string like:
String [] command = {"ping google.com", "ping yahoo.com"};
However, this showed me an error.
I appreciate your help on this.
Use a loop:
String [] commands = {"ping google.com", "ping yahoo.com"};
for(String command: commands) {
Process process = Runtime.getRuntime().exec(command);
//more stuff
}
I found this as one of the ways to run (using exec() method) python script from java. I have one simple print statement in python file. However, my program is doing nothing when I run it. It neither prints the statement written in python file nor throws an exception. The program just terminates doing nothing:
Process p = Runtime.getRuntime().exec("C:\\Python\\Python36-32\\python.exe C:\\test2.py");
Even this is not creating the output file:
Process p = Runtime.getRuntime().exec("C:\\Python\\Python36-32\\python.exe C:\\test2.py output.txt 2>&1");
What is the issue?
I think you could try your luck with the ProcessBuilder class.
If I read the Oracle documentation correctly, the std inputs and outputs are directed to pipes by default but the ProcessBuilder has an easy method for you to explicitly set output (or input) to a file on your system or something else.
If you want your Python program to use the same output as your Java program (likely stdout and stderr), you can use stg like this:
ProcessBuilder pb = new ProcessBuilder("C:\\Python\\Python36-32\\python.exe", "C:\\test2.py");
pb.redirectOutput(Redirect.INHERIT);
Process p = pb.start();
You can use the ProcessBuilder API, redirecting the output to a file and then wait for the result.
public class Main {
public static final String PYTHON_PATH = "D:\\Anaconda3\\python.exe";
public static final String PATH_TO_SCRIPT = "D:\\projects\\StartScript\\test.py";
public static void main(String[] args) throws IOException, InterruptedException {
ProcessBuilder builder = new ProcessBuilder();
builder.command(PYTHON_PATH, PATH_TO_SCRIPT);
// Redirect output to a file
builder.redirectOutput(new File("output.txt"));
builder.start().waitFor();
// Print output to console
ProcessBuilder.Redirect output = builder.redirectOutput();
File outputFile = output.file();
BufferedReader br = new BufferedReader(new FileReader(outputFile));
String st;
while ((st = br.readLine()) != null) {
System.out.println(st);
}
}
}
The python file test.py contains a simple print statement:
print("Hello from python")
I guess it would be even simpler, if you do not need to wait for the result.
Using the Process API should work, too.
Like in your example (I am using the same constants declared above):
Process p = Runtime.getRuntime().exec(PYTHON_PATH + " " + PATH_TO_SCRIPT);
p.waitFor();
byte[] buffer = new byte[1024];
byte[] errBuffer = new byte[1024];
p.getInputStream().read(buffer);
p.getErrorStream().read(errBuffer);
System.out.println(new String(buffer));
System.out.println(new String(errBuffer));
To see the output of the print statement, you need to wait and redirect the streams. Same for the error stream.
Now if you break the python script like this:
print("Hello from python')
you should be able to see the error printed as well.
One way to start a python process is using an entrypoint - test.cmd
echo Hello
python hello.py
here is hello.py
#!/usr/bin/env python3
import os
if not os.path.exists('dir'):
os.makedirs('dir')
Here is my Java code:
public static void main(String[] args) throws IOException {
try {
Process p = Runtime.getRuntime().exec("test.cmd");
p.waitFor();
Scanner sc = new Scanner(p.getInputStream());
while(sc.hasNextLine()){
System.out.println(sc.nextLine());
}
sc.close();
} catch (Exception err) {
err.printStackTrace();
}
}
I want to execute a Java CLI-program from within another Java program and get the output of the CLI-program. I've tried two different implementations (using runtime.exec() and ProcessBuilder) and they don't quite work.
Here's the peculiar part; the implementations work (catch the output) for when executing commands such as pwd but for some reason they do not catch the output of a Hello World java program executed with java Hello.
Execution code:
public static void executeCommand(String command)
{
System.out.println("Command: \"" + command + "\"");
Runtime runtime = Runtime.getRuntime();
try
{
Process process = runtime.exec(command);
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(process.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(process.getErrorStream()));
// read the output from the command
System.out.println("Standard output of the command:\n");
String s = null;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// read any errors from the attempted command
System.out.println("Standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
} catch (Exception e)
{
e.printStackTrace();
}
}
Example output
Command: "cd /Users/axelkennedal/Desktop && java Hello"
Standard output of the command:
Standard error of the command (if any):
Command: "pwd"
Standard output of the command:
/Users/axelkennedal/Dropbox/Programmering/Java/JavaFX/Kode
Standard error of the command (if any):
I have verified that Hello does indeed print "Hello world" to the CLI when running Hello directly from the CLI instead of via executeCommand().
Hello world
public class Hello
{
public static void main(String[] args)
{
System.out.println("Hello world!");
}
}
This "cd /Users/axelkennedal/Desktop && java Hello" is not one command but two commands separated by the &&. In general it means do the first command and if the first command succeeds do the second command. You can't pass this as a single command but you can implement the logic yourself:
eg to execute "cmd1 && cmd2"
if (Runtime.getRuntime().exec("cmd1").waitFor() == 0) {
Runtime.getRuntime().exec("cmd2").waitFor();
}
However, because in this case cmd1 is to change directories there is a better way, which is to use the directory function of ProcessBuilder instead of the first command.
Process p = new ProcessBuilder("java","hello")
.directory(new File("/Users/axelkennedal/Desktop"))
.start();
I need to execute a python script inside a java mapreduce program.
Here, in the mapper class , I need execute the the python command :
python methratio.py --ref=../refernce/referncefile -r -g --out=Ouputfile ./Inputfile
Here the Inputfile is the input file in hdfs and the outputfile (in hdfs) is where the python script writes the ouput.
Can I use process builder or any other better options are there ??
I don't know if this can help you, but you can execute system commands in this way in java:
public static void main(String[] args) throws IOException {
String s = null;
String command = "python <your_command>";
Process p = Runtime.getRuntime().exec(command);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
// 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);
}
}
You can see a detailed example in http://alvinalexander.com/java/edu/pj/pj010016
Hope this help you :D
I am trying to run R script in java program and output the result into text file.
Here is my java code:
import java.io.*;
public class rclass {
public static void main(String[] args) {
try {
String line;
Process p = Runtime.getRuntime().exec("RScript /Users/test.R iphone5 2012-12-16 2013-01-03");
p.waitFor();
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while((line = input.readLine()) != null) {
System.out.println(line);
}
input.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
Here's how I output r result into text file:
out<-capture.output(scores)
cat(out, file="/Users/mmmmmm/Desktop/result.txt", sep="\n",append=TRUE)
When I run the java code, there's no output from my r script into text file. But when I run the command from terminal, it works well. I cannot to find the problem. Could anyone please give me some suggestions?
This is not a solution because I can't reproduce the problem. But why not to output the result using Rscript in a file?
For example , You can do somthing like this to put the output and error in the same file
RScript /Users/test.R iphone5 2012-12-16 2013-01-03 > result.txt 2>&1