我正在尝试在执行我的java代码期间运行python脚本,因为它将取决于从python脚本接收的输出。到目前为止,我尝试使用jythonc,但遗憾的是没有成功,现在我试图使用java Runtime和java Process来执行python脚本。
现在我在尝试调用python脚本时遇到了问题。我觉得好像甚至没有调用脚本,因为到达下一页只需要不到几秒钟....
问题可能是我如何调用python脚本?我试图通过Web应用程序运行...
以下是我的一些代码:
String run = "cmd /c python duplicatetestingoriginal.py" ;
boolean isCreated = fwr.writeFile(BugFile, GD, 500, true, 5, "LET");
if(isCreated){
try{
r = Runtime.getRuntime();
p = r.exec(run);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String line = "";
while ((line = stdInput.readLine()) != null) {
System.out.println(line);
}
while ((line = stdError.readLine()) != null) {
errorW.write(line);
}
int exitVal = p.waitFor();
arrayList = fwr.readResults();
}catch(Exception e){
}
}
else{
// troubleshoot....
}
答案 0 :(得分:3)
而不是命令的String,将其拆分为块并创建一个String []。我认为无需陈述cmd /c
。
这是我的应用程序的示例代码:
//Running on windows
command = new String[4];
command[0]=directory.getCanonicalPath()+"/data/ExtenalApp.exe"; //extenal commandline app, not placed in path, but in subfolder
command[1]=directory.getCanonicalPath()+"/data/SomeFile.txt"; //file needed for the external app, sent as an argument
command[2]=arg1; //argument for the app
command[3]=arg2; //argument for the app
//Running on Mac
command = new String[6];
command[0]="python";
command[1]=directory.getCanonicalPath()+"/data/wp.py"; //path to the script
command[2]="-F"; //argument/Flag/option
command[3]="--dir="+path; //argument/option
command[4]="--filename="+filename; //argument/option
command[5]=argument; //argument/option
Process process = Runtime.getRuntime().exec(command);
process.waitFor();
process.destroy();
我不处理输入/输出流,因为脚本/应用程序不需要输入,仅在完成时输出,没有什么重要的。对你来说可能不是这样。