From last day, I have been trying to execute a command on Terminal (MAC) using JAVA but whatever I do nothing is working.
I have the following 2 commands that I want to execute and get the output back in JAVA
source activate abc_env
python example.py
Till now, I have tried the following methods without any output
String[] command = new String[] { "source activate abc_env", "python example.py"};
String result = executeCommands(command);
Here is my executeCommands method
private static String executeCommands(String[] command) {
StringBuffer output = new StringBuffer();
Process p;
try {
for(int i=0; i< command.length;i++)
{
p = Runtime.getRuntime().exec(command[i]);
p.waitFor();
BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
System.out.println("Error output: " + p.exitValue());
System.out.println("Output:" + output);
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("Here");
}
return output.toString();
}
This gives me the following exception
Cannot run program "source": error=2, No such file or directory
I searched online and people say that source won't work like this and I should change the command to
String[] command = new String[] { "bash -c 'source activate abc_env'", "python example.py"};
Now, I donot get the exception but the command still does not work and it returns '2' as exitValue()
Then I tried to execute the commands as a script
#!/bin/bash
source activate abc_env
python example.py
I get the following exception when I read the .sh file as string and pass it to command
Cannot run program "#!/bin/bash": error=2, No such file or directory
So, my question is how to run the source command followed by python command properly through Java ? My final goal is execute some python from Java.
EDIT1:
If I try the following command and print the output stream
String[] command = {
"/bin/bash",
"-c",
"source activate cvxpy_env"
};
executeCommand(command));
Output Stream:
ExitValue:1
ErrorOutput:/bin/bash: activate: No such file or directory
If I try the same command but with single quotes around 'source activate abc_env'. I get the following output
ExitValue:127
ErrorOutput:/bin/bash: source activate cvxpy_env: command not found
Solution:
String[] command = {
"/bin/bash",
"-c",
"source /Users/pc_name/my_python_library/bin/activate abc_env;python example.py"
};
According to the Javadoc, Runtime.exec(String) breaks the command into the command-args list using a StringTokenizer, which will probably break your command into:
bash
-c
'source
activate
abc_env'
Which is obviously not what you want. What you should do is probably use the version of Runtime.exec(String[]) that accepts a ready list of arguments, passing to it new String[] {"bash", "-c", "source activate abc_env"}.
Now, to get an idea why it's not working, you should not only read from its stdout but also from stderr, using p.getErrorStream(). Just print out what you read, and it will be a great debugging aid.
Re: your edit. Now it looks like it's working fine, as far as Java and bash are concerned. The output "activate: No such file or directory" is probably the output from the successful run of the source command. It just that source can't find the activate file. Is it in the working directory? If not, you probably should have "cd /wherever/your/files/are; source activate cvxpy_env". Oh, and if your python script depends on whatever side-effects the source command has, you probably have to execute it in the same bash instance, that is:
String[] command = {
"/bin/bash",
"-c",
"cd /wherever/your/files/are && source activate cvxpy_env && python example.py"
};
Or better yet, pack it all into a single shell script, and then just Runtime.exec("./my_script.sh") (don't forget to chmod +x it, though).
Try
String[] command = {
"/bin/bash",
"-c",
"source activate abc_env; " + "python example.py"
};
Related
I have a list of files for which I have to run the vimdiff command and save the output as a html file.I am doing this with Java. Below is the command I am trying to execute
String cmd = "vimdiff -c 'set foldlevel=9999' src/test/resources/testdata/output/html_output_before_changes/file1.html src/test/resources/testdata/output/html_output_after_changes/file2.html -c TOhtml -c 'w! different.html' -c 'qa!'"
When I run the below code, the code is getting executed. But I am not able to see the file getting generated.
Runtime rt = Runtime.getRuntime();
Process process = rt.exec(cmd);
The command is running fine when executed from a terminal. But its not working when executed inside a java program. Can someone help me with this issue? I did a lot of search but not able to proceed with this.
You're using :TOhtml and write the result as different.html. If you're not sure where to locate the file, check the current working directory of the Java process, do a file search of your hard disk, or specify an absolute path in the Vim command to be sure.
You won't see anything from Vim's operation itself. Using process.getInputStream(), you could obtain what Vim wrote to the terminal during its operation, but that would just amount to a garble of characters, as Vim is using special ANSI escape sequences to control the terminal, position the cursor, etc.
To use Vim non-interactively, it is recommended to pass the following options:
-T dumb Avoids errors in case the terminal detection goes wrong.
-n No swapfile.
-i NONE Ignore the |viminfo| file (to avoid disturbing the
user's settings).
-c 'set nomore' Suppress the more-prompt when the screen is filled
with messages or output to avoid blocking.
Without a possibility to interact with Vim (from inside your Java program), a troubleshooting tip is enabling verbose logging: You can capture a full log of a Vim session with -V20vimlog. After quitting Vim, examine the vimlog log file for errors.
After Two days I found the below Solution:
I added the vimdiff command to a shell script and executed it using the following method and it worked like a gem.
Java method
try {
File[] uiDiffDir = getFiles();
for (File file : uiDiffDir) {
String[] cmd = {"sh", shellScriptPath, file1, file2,
outputfile};
Process p = Runtime.getRuntime().exec(cmd);
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(
p.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
shell.sh
vimdiff -c 'set foldlevel=9999' $1 $2 -c TOhtml -c 'w! '"$3"'' -c 'qa!'
Note:
file1 will be passed as a argument in the place of $1
file2 will be passed as a argument in the place of $2
outputfile will be passed as a argument in the place of $3
I want to run a script with ssh from java. The script takes a number as parameter. I launch this code :
String myKey="/home/my_key.pem";
Runtime runtime = Runtime.getRuntime();
String commande = "ssh -i "
+myKey+" ubuntu#ec2-56-75-88-183.eu-west-1.compute.amazonaws.com './runScript.bash 8000'";
Process p = runtime.exec(commande);
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String line = reader.readLine();
while (line != null) {
System.out.println(line);
line = reader.readLine();
}
p.waitFor();
I obtain this error :
bash: ./runScript.bash 8000: No such file or directory
The name of file is correct. chmod given to runScript.bash is 777.
When i run the command line directly from bash it works. But from IDE, it does not.
How can i do to run this commande line correctly please ?
The error makes it clear:
bash: ./runScript.bash 8000: No such file or directory
This indicates that the shell is trying to invoke a script called ./runScript.bash 8000 -- with the space and the 8000 in the filename of the script.
It's rare for me to be telling anyone to use fewer quotes, but, well, this is actually a case where that would fix things.
Better would be to avoid double evaluation altogether:
Runtime.exec(new String[] {
"ssh",
"-i", myKey,
"ubuntu#ec2-56-75-88-183.eu-west-1.compute.amazonaws.com",
"./runScript 8000"
})
I tried to run command line from Java code.
public void executeVcluto() throws IOException, InterruptedException {
String command = "cmd /c C:\\Users\\User\\Downloads\\program.exe C:\\Users\\User\\Downloads\\file.txt 5 >> C:\\Users\\User\\Downloads\\result.txt";
Process process = Runtime.getRuntime().exec(command);
process.waitFor();
if (process.exitValue() == 0) {
System.out.println("Command exit successfully");
} else {
System.out.println("Command failed");
}
}
However, the file where output result should be written result.txt is not created. When I execute this command from cmd on windows the file is created and the result is written in it. I get Command exit successfully message. Could someone help me?
output redirection is shell feature, java Process does not understand that.
Some other alternatives are
1. create a single batch file with above lines and invoke it using ProcessBuilder/Runtime
2. Use ProcessBuilder and redirect output using output streams.
Example (it is for shell, will work for batch files too) is here
ProcessBuilder builder = new ProcessBuilder("cmd", "/c", "C:\\Users\\User\\Downloads\\program.exe", "C:\\Users\\User\\Downloads\\file.txt" , "5");
builder.redirectOutput(new File("C:\\Users\\User\\Downloads\\result.txt"));
builder.redirectError(new File("C:\\Users\\User\\Downloads\\resulterr.txt"));
Process p = builder.start(); // throws IOException
(above is tweaked from Runtime's exec() method is not redirecting the output)
Try cmd.exe, including a path, if necessary.
You're creating an entirely new process, which is different than giving a command to a shell.
Is it possible to open the command prompt (and I guess any other terminal for other systems), and execute commands in the newly opened window?
Currently what I have is this:
Runtime rt = Runtime.getRuntime();
rt.exec(new String[]{"cmd.exe","/c","start"});
I've tried adding the next command after the "start", I've tried running another rt.exec containing my command, but I can't find a way to make it work.
If it matters, I'm trying to run a command similar to this:
java -flag -flag -cp terminal-based-program.jar
EDIT Unfortunately I have had some strange findings. I've been able to successfully launch the command prompt and pass a command using this:
rt.exec("cmd.exe /c start command");
However, it only seems to work with one command. Because, if I try to use the command separator like this, "cmd.exe /c start command&command2", the second command is passed through the background (the way it would if I just used rt.exec("command2");). Now the problem here is, I realized that I need to change the directory the command prompt is running in, because if I just use the full path to the jar file, the jar file incorrectly reads the data from the command prompt's active directory, not the jar's directory which contains its resources.
I know that people recommend staying away from rt.exec(String), but this works, and I don't know how to change it into the array version.
rt.exec("cmd.exe /c cd \""+new_dir+"\" & start cmd.exe /k \"java -flag -flag -cp terminal-based-program.jar\"");
If you are running two commands at once just to change the directory the command prompt runs in, there is an overload for the Runtime.exec method that lets you specify the current working directory. Like,
Runtime rt = Runtime.getRuntime();
rt.exec("cmd.exe /c start command", null, new File(newDir));
This will open command prompt in the directory at newDir. I think your solution works as well, but this keeps your command string or array a little cleaner.
There is an overload for having the command as a string and having the command as a String array.
You may find it even easier, though, to use the ProcessBuilder, which has a directory method to set your current working directory.
Hope this helps.
public static void main(String[] args) {
try {
String ss = null;
Process p = Runtime.getRuntime().exec("cmd.exe /c start dir ");
BufferedWriter writeer = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
writeer.write("dir");
writeer.flush();
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
System.out.println("Here is the standard output of the command:\n");
while ((ss = stdInput.readLine()) != null) {
System.out.println(ss);
}
System.out.println("Here is the standard error of the command (if any):\n");
while ((ss = stdError.readLine()) != null) {
System.out.println(ss);
}
} catch (IOException e) {
System.out.println("FROM CATCH" + e.toString());
}
}
The following works for me on Snow Leopard:
Runtime rt = Runtime.getRuntime();
String[] testArgs = {"touch", "TEST"};
rt.exec(testArgs);
Thing is, if you want to read the output of that command, you need to read the input stream of the process. For instance,
Process pr = rt.exec(arguments);
BufferedReader r = new BufferedReader(new InputStreamReader(pr.getInputStream()));
Allows you to read the line-by-line output of the command pretty easily.
The problem might also be that MS-DOS does not interpret your order of arguments to mean "start a new command prompt". Your array should probably be:
{"start", "cmd.exe", "\c"}
To open commands in the new command prompt, you'd have to use the Process reference. But I'm not sure why you'd want to do that when you can just use exec, as the person before me commented.
You just need to append your command after start in the string that you are passing.
String command = "cmd.exe /c start "+"*your command*";
Process child = Runtime.getRuntime().exec(command);
String[] command = {"cmd.exe" , "/c", "start" , "cmd.exe" , "/k" , "\" dir && ipconfig
\"" };
ProcessBuilder probuilder = new ProcessBuilder( command );
probuilder.directory(new File("D:\\Folder1"));
Process process = probuilder.start();
You can use any on process for dynamic path on command prompt
Process p = Runtime.getRuntime().exec("cmd.exe /c start dir ");
Process p = Runtime.getRuntime().exec("cmd.exe /c start cd \"E:\\rakhee\\Obligation Extractions\" && dir");
Process p = Runtime.getRuntime().exec("cmd.exe /c start cd \"E:\\oxyzen-workspace\\BrightleafDesktop\\Obligation Extractions\" && dir");
Please, place your command in a parameter like the mentioned below.
Runtime.getRuntime().exec("cmd.exe /c start cmd /k \" parameter \"");
You have to set all \" (quotes) carefully. The parameter \k is used to leave the command prompt open after the execution.
1) to combine 2 commands use (for example pause and ipconfig)
Runtime.getRuntime()
.exec("cmd /c start cmd.exe /k \"pause && ipconfig\"", null, selectedFile.getParentFile());
2) to show the content of a file use (MORE is a command line viewer on Windows)
File selectedFile = new File(pathToFile):
Runtime.getRuntime()
.exec("cmd /c start cmd.exe /k \"MORE \"" + selectedFile.getName() + "\"\"", null, selectedFile.getParentFile());
One nesting quote \" is for the command and the file name, the second quote \" is for the filename itself, for spaces etc. in the name particularly.
I am trying to execute a program from the Java code. Here is my code:
public static void main(String argv[]) {
try {
String line;
Process p = Runtime.getRuntime().exec(new String[]{
"/bin/bash", "-c", "executable -o filename.txt"});
BufferedReader input = new BufferedReader(
new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
System.out.println(line);
}
input.close();
} catch (Exception err) {
err.printStackTrace();
}
}
My OS is Mac OS X 10.6.
Now, the executable I am trying to run is supposed to spit the output to filename.txt. If I take this command and run it on the terminal, it works fine and the filename.txt gets populated also. But, from my java program the file is not created.
if instead I use executable > filename.txt then the filename.txt is created but is empty. Not sure what's wrong here. The executable I am trying to run is Xtide (if that helps).
I would really appreciate any help I can get.
Thanks,
You cannot redirect output to file and read the output in java. It's one or the other. What you want is this:
Process p = Runtime.getRuntime().exec(new String[]{
"/bin/bash", "-c", "executable -o filename.txt"});
p.waitFor();
BufferedReader input = new BufferedReader(
new InputStreamReader(new FileInputStream("filename.txt")));
while ((line = input.readLine()) != null) {
System.out.println(line);
}
The main changes are:
p.waitFor(), since process execution is asynchronous, so you have to wait for it to complete.
The data is read from the file rather than from the output of the process (since this will be empty.)
The answer from mdma works (and I voted it up), but you might also want to consider the version where you do read the output stream directly from executable:
Process p = Runtime.getRuntime().exec(new String[]{
"/bin/bash", "-c", "executable"});
p.waitFor();
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream())_;
while ((line = input.readLine()) != null) {
System.out.println(line);
}
Correct me if I am wrong, but the symptoms are as follows:
exec("/usr/bash", "-c", "executable > filename.txt") creates an empty file.
exec("/usr/bash", "-c", "executable -o filename.txt") does not create a file.
One or both of the above gives an exit code of 255 when you look at it.
When you run the command from the command line as executable -o filename.txt or executable > filename.txt it works as expected.
In the light of the above, I think that the most likely cause is that /bin/bash is not finding the executable when you launch it from Java. The fact that the first example does create an empty file means that /bin/bash is doing something. But if you try to run
$ unknown-command > somefile.txt
from a bash shell prompt you will get an error message saying that the command cannot be found and an empty "something.txt" file. (You would not see the error message in your Java app because it is being written to stderr, and you are not capturing it.) The reason that the empty "something.txt" file is created is that it is opened by the shell before it attempts to fork and exec the "executable".
If this is the problem, then the simple solution is to use the absolute pathname for the executable.
Also, if you are not doing any command line redirection or other shell magic, there is no need to run the executable in a new bash instance. Rather, just do this:
Process p = Runtime.getRuntime().exec("executable", "-o", filename.txt");
then wait for the process to complete and check the exit code before trying to read the file contents.