I am trying to run python script inside a java code by creating Process with Runtime
This is the contents of my java code:
String pythonPath = "/usr/local/bin/python3";
String runTestPath = "/Users/tuko/Documents/eclipse-workspace/WebLang_v2/runTests.py";
String[] cmd = new String[] {pythonPath, runTestPath};
Process process = Runtime.getRuntime().exec(cmd);
This is the contents of my python script:
import os
import time
import subprocess
try:
output = subprocess.check_output("behave",shell=True)
except Exception as e:
print(e)
This is the output:
Command 'behave' returned non-zero exit status 127.
Java doesn't recognize "behave" command. How to make this command recognizable by java
Related
Currently trying to execute a .jar file programmatically. But to test out java, I tried running the the following:
val p = ProcessBuilder("cmd.exe", "/c", "java", "-version").start()
val results: List<String> = p.inputStream.bufferedReader().readLines()
assertThat("Results should contain java version: ", results, hasItem(containsString("java version")))
However, nothing seems to output.
I am successfully able to run:
val pb = ProcessBuilder("cmd.exe", "/c", "echo", "hello world")
I have tried adding a working directory where the java executable is located, but nothing happens.
I am running out of ideas on how to make this work. If I run cmd and type out java -version I get the version information.
What else could I do to get this to work?
ProcessBuilder writes the result of command java -version to error output Process.errorStream, not Process.inputStream.
Try this code:
val results: List<String> = p.errorStream.bufferedReader().readLines()
Also you may try Koproc lib
It's a small Kotlin lib to run process and execute commands based on Java ProcessBuilder
You may run java process with timeout = 120 sec :
val koproc = "java -jar some.jar".startProcess { timeoutSec = 120 }
koproc.use {
println("Out: ${it.readAvailableOut}")
println("Err: ${it.readAvailableErrOut}")
}
println("Full result after closing: ${koproc.result}")
Run cmd command:
// 'cmd.exe' process will be closed after timeout
val commandResult = "cmd.exe dirs".startCommand { timeoutSec = 1 }
// But you will get the output
println("Out: ${commandResult.out}")
See examples in unit tests: https://github.com/kochetkov-ma/koproc/blob/main/src/test/kotlin/ru/iopump/koproc/ExtensionKtIT.kt
I'm trying to train a neural network to play Halite 3. The provided interface is a bash script which:
1. compiles my bot
2. calls the binary file with a string to run the bot java myBot
I'm trying to run this script from Java to train the network.
I've tried using a ProcessBuilder to run the script as well as the binary in the script. Running the script produces no output, and using echo I've determined that the program terminates when javac is called in the script. Removing that call, it terminates when the program is run.
I've tried calling the program directly as well using ProcessBuilder, and this does indeed produce output. The issue is it doesn't run the bots properly saying it can't find the file. I've tried changing the path to be relative to different directory levels as well as the absolute path (the java command doesn't seem to like absolute paths?).
Calling the binary directly:
List<String> cmd = new ArrayList<>();
cmd.add(dir+ "/src/halite");
// Replay
cmd.add("--replay-directory");
cmd.add(dir+"/replays/");
// Options
cmd.add("--results-as-json");
cmd.add("--no-logs");
// Dimensions
cmd.add("--width");
cmd.add("16");
cmd.add("--height");
cmd.add("16");
// Players
cmd.add("\"java -cp . myBot\"");
cmd.add("\"java -cp . myBot\"");
Process proc = new ProcessBuilder(cmd).start();
InputStream is = proc.getInputStream();
Scanner s = new Scanner(is);
while (s.hasNext()){
System.out.println((String) s.next());
}
This code does produce a JSON, however, I get an error in my logs saying that the bots do not run.
I'm using Ubuntu and I just want to open the terminal from Java and execute this command make iris sim. After that keep the terminal open until the user click any key.
This is my code, but it's not working correctly:
String []commands= {"make", "iris", "sim"};
String[] cmdArray = {"/usr/bin/xterm", "-e"};
Process p = Runtime.getRuntime().exec(cmdArray, commands);
You are using the exec command wrong. The second parameter is not an array of "commands" but an array of environment variables. See the JavaDocs.
Instead, simply call your command:
Process p = Runtime.getRuntime().exec("/usr/bin/xterm -e make iris sim");
Note that this will create a new process. If you want to wait for this process call p.waitFor();.
I have been looking for an answer for how to execute a java jar file through python and after looking at:
Execute .jar from Python
How can I get my python (version 2.5) script to run a jar file inside a folder instead of from command line?
How to run Python egg files directly without installing them?
I tried to do the following (both my jar and python file are in the same directory):
import os
if __name__ == "__main__":
os.system("java -jar Blender.jar")
and
import subprocess
subprocess.call(['(path)Blender.jar'])
Neither have worked. So, I was thinking that I should use Jython instead, but I think there must a be an easier way to execute jar files through python.
Do you have any idea what I may do wrong? Or, is there any other site that I study more about my problem?
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
I used the following way to execute tika jar to extract the content of a word document. It worked and I got the output also. The command I'm trying to run is "java -jar tika-app-1.24.1.jar -t 42250_EN_Upload.docx"
from subprocess import PIPE, Popen
process = Popen(['java', '-jar', 'tika-app-1.24.1.jar', '-t', '42250_EN_Upload.docx'], stdout=PIPE, stderr=PIPE)
result = process.communicate()
print(result[0].decode('utf-8'))
Here I got result as tuple, hence "result[0]". Also the string was in binary format (b-string). To convert it into normal string we need to decode with 'utf-8'.
With args: concrete example using Closure Compiler (https://developers.google.com/closure/) from python
import os
import re
src = test.js
os.execlp("java", 'blablabla', "-jar", './closure_compiler.jar', '--js', src, '--js_output_file', '{}'.format(re.sub('.js$', '.comp.js', src)))
(also see here When using os.execlp, why `python` needs `python` as argv[0])
How about using os.system() like:
os.system('java -jar blabla...')
os.system(command)
Execute the command (a string) in a subshell. This is implemented by calling the Standard C function system(), and has the same limitations. Changes to sys.stdin, etc. are not reflected in the environment of the executed command.
I have a jar say test.jar having TestJar as its main class, a shell script jar_executor.sh,and a java file. My test.jar will return 1 if we pass 1 as an argument and 2 if we pass any other value.
My shell script is executing test.jar as follow
#!/usr/bin/ksh
java TestJar 1 -cp test.jar
return_code=$?
exit $return_code
In java file I am creating a process and executing shell script and taking its exitvalue with following code
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(sh jar_executor.sh);
int exitVal = process.waitFor();
System.out.println(exitVal);
This exitVal variable should print 1 or 2 as per argument we are passing but it is printing 255 everytime.
If I use echo $return_code in shell script then I am getting correct value.
Please help me why I am getting value 255 with exit. Thanks in advance!!!
255 or -1 is an application defined exit code, you would have to read the code to know what it means.
A Java application which exits normally, returns 0 and if it throws an Exception, returns 1.
Go to your workspace library, workspace.metadata.plugins\org.eclipse.e4.workbench
and remove the workbench file :) . after that you can restart eclipse
It looks like it might be a Java bug. Others have reported issues similar to what you've seen; see this Java bug report. The Java devs don't think there's a bug but I'm suspicious. The code JRE uses to get the return value from a spawned process is hairy, and I wouldn't be surprised if there's a race condition or other concurrency bug.
I'm guessing that the JRE fails to capture the return code if the spawned process exits very quickly. If my suspicion is correct, adding sleep 1 to your shell script will cause it to work.
Your shell script does not call java correctly:
java TestJar 1 -cp test.jar
You need to set the options for the java command before you mention your main class name. All arguments after your main class name are arguments for your main class and are no longer options for the java VM. So in your case there is no classpath specified for java. I get the following error message when I execute your script: Error: Could not find or load main class TestJar. To fix, you have just to re-order the arguments in your jar_executor.sh script:
java -cp test.jar TestJar 1
I cannot reproduce the 255 on my PC, so I can only guess where that comes from: Either your java command returns an error code of 255 instead of 1 when it fails to load the main class or your korn shell (/usr/bin/ksh) sets this return value when the script is aborted.
Here are all sources I used:
jar_executor.sh
#!/bin/sh -e
java -cp test.jar TestJar 2
return_code=$?
exit $return_code
TestJar.java
public class TestJar {
public static void main(final String[] args) {
System.exit(Integer.parseInt(args[0]));
}
}
JarRunner.java
import java.io.IOException;
public class JarRunner {
public static void main(final String[] args) throws IOException, InterruptedException {
final Runtime runtime = Runtime.getRuntime();
final Process process = runtime.exec("sh jar_executor.sh");
final int exitVal = process.waitFor();
System.out.println(exitVal);
}
}
When I now run java -cp bin JarRunner, I get the output 2 as expected.
You're probably wrong in invoking the script. Try:
Process process = runtime.exec("sh -c jar_executor.sh");
Note the "-c" flag that means you're calling the shell to execute the command.