简体   繁体   中英

How to run python script (and receive output) from java/spring-boot project which is inside a docker container?

I am trying to migrate services on my Ubuntu 16.04 server to docker 18.09.2 (so that I can leverage kubernetes). My problem is getting a Jar to work in Docker the way it works in my local machine and server.

Namely, I am trying to run a python script inside of my Java Spring Boot Application, capture the output of the Python, and then display the text. This works fine on my local machine , but when I build it on the docker base image and run it, nothing happens (ie null value is returned from Buffered Reader)

The base docker image is 'openkbs/jre-mvn-py3'. The 'HelloWorld.py' file is located in the SpringBoot project directory.

Taking from openkbs's documentation ( https://hub.docker.com/r/openkbs/jre-mvn-py3/ ), I have tried a few different command's in my processString, but nothing is working. Commands like:

docker run -it --rm openkbs/jdk-mvn-py3 python3 -c 'print("Hello World")'

docker run -i --rm openkbs/jdk-mvn-py3 python3 < HelloWorld.py

Here are my relevant configurations and lines of code:

Dockerfile:

FROM openkbs/jdk-mvn-py3
ADD target/dockerMaster.jar dockerMaster.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "dockerMaster.jar"]

Java:

    @RequestMapping("/pytest")
    public String pytest() {
        Runtime rt = Runtime.getRuntime();
        String processString = "python3 HelloWorld.py";
        System.out.println(processString);

        try {
            Process extractProcess = rt.exec(processString);
            BufferedReader input = new BufferedReader(new InputStreamReader(extractProcess.getInputStream()));
            String pyString = input.readLine();
            return new String("<PYSTUFF>SUCCESS " + pyString + "</PYSTUFF>");
        } catch (IOException e) {
            e.printStackTrace();
            return new String("<FAIL>PYTHON DID NOT RUN</FAIL>");
        } 
    }

Python:

print("Hello World")

you are not putting your HelloWorld.py file into the container that is why its not working what you need to do is add HelloWorld.py into the container and also make sure python is installed inside the container.

FROM openkbs/jdk-mvn-py3
ADD target/dockerMaster.jar dockerMaster.jar
ADD target/HelloWorld.py HelloWorld.py
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "dockerMaster.jar"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM