在J中运行Python脚本

2024-09-30 20:21:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在java代码执行期间运行python脚本,因为它将取决于从python脚本接收到的输出。到目前为止,我尝试过使用jythonc,不幸的是没有成功,现在我尝试使用javaRuntime和javaProcess来执行python脚本。

现在我在尝试调用python脚本时遇到了一个问题。我觉得它甚至没有调用脚本,因为它只需要不到几秒钟就可以进入下一页。。。。

问题是我如何调用python脚本吗??我正试图通过一个网络应用程序运行这个。。。

以下是我的一些代码:

    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....

    }

Tags: run脚本newreadlinestringlinejavanull
1条回答
网友
1楼 · 发布于 2024-09-30 20:21:46

不是命令的字符串,而是将其拆分为块并生成一个字符串[]。我认为不需要声明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();

我不处理输入/输出流,因为脚本/应用程序不需要输入,只在完成时输出,没有什么重要的。对你来说可能不是这样。

相关问题 更多 >