簡體   English   中英

使用JAVA為AWS CloudFormation運行python文件

[英]Run python file for AWS CloudFormation using JAVA

我想運行一個可以使用JAVA運行AWS CloudFormation模板的python文件。 我正在用JAVA代碼傳遞python文件。 當我運行JAVA代碼時,它會暫停在以下狀態:

單編譯:

單行:

如果我從終端運行Python文件,它將運行完美。

Java代碼:

private void RunPythonActionPerformed(java.awt.event.ActionEvent evt) {                                          
    String pythonScriptPath = "path to python file";
    String[] cmd = new String[2];
    cmd[0] = "python"; // check version of installed python: python -V
    cmd[1] = pythonScriptPath;
    // create runtime to execute external command
    Runtime rt = Runtime.getRuntime();
    Process pr = null;
    try {
        pr = rt.exec(cmd);
        // retrieve output from python script
    } catch (IOException ex) {
        Logger.getLogger(Page2.class.getName()).log(Level.SEVERE, null, ex);
    }

BufferedReader bfr = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line = "";
    try {
        while((line = bfr.readLine()) != null) {
        // display each output line form python script
        System.out.println(line);
        }        
        // TODO add your handling code here:
    } catch (IOException ex) {
        Logger.getLogger(Page2.class.getName()).log(Level.SEVERE, null, ex);
    }
}

<complete path to your python source file>為您復制工作代碼處提供源文件的<complete path to your python source file> 對我來說輸出是Python 3.6.5

package com.samples;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ProcessBuilderSample {

    public static void main(String [] args) throws IOException {
        RunPythonActionPerformed();
    }

    private static void RunPythonActionPerformed() throws IOException {                                          
        String pythonScriptPath = "python -V";
        Process p = Runtime.getRuntime().exec(pythonScriptPath);

        BufferedReader bfr = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line = "";
        try {
            while((line = bfr.readLine()) != null) {
                // display each output line form python script
                System.out.println(line);
            }        
            // TODO add your handling code here:
        } catch (IOException ex) {
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM