如何在Java程序中使用Docker容器运行Python脚本?

huangapple go评论117阅读模式
英文:

How to run a python script in Java program using Docker container?

问题

Dockerfile:

FROM openjdk:8-jdk-alpine
ARG JAR_FILE=target/*.jar
ARG SCRIPT_FILE=src/main/resources/script/test.py

COPY ${JAR_FILE} app.jar
COPY ${SCRIPT_FILE} test.py
ENTRYPOINT ["java","-jar","/app.jar"]

现在我的应用程序有一行代码执行一个Python脚本,类似于这样:
代码片段:

String interpretor = "python";
String scriptFile = "test.py";
String arguments = "ping";
String[] cmd = {interpretor,scriptFile,arguments};

try {
    Process p = Runtime.getRuntime().exec(cmd);
    ...
}

**异常**

java.io.IOException: 无法运行程序 "python":错误=2,没有那个文件或目录


任何帮助都会感激。谢谢。

<details>
<summary>英文:</summary>

i am new to docker and trying to dockerize a java app, which in turn calls a python script

Dockerfile :

    FROM openjdk:8-jdk-alpine
    ARG JAR_FILE=target/*.jar
    ARG SCRIPT_FILE=src/main/resources/script/test.py
    
    COPY ${JAR_FILE} app.jar
    COPY ${SCRIPT_FILE} test.py
    ENTRYPOINT [&quot;java&quot;,&quot;-jar&quot;,&quot;/app.jar&quot;]

Now my App has a line of code which executes a python script, something like this :
Code snippet : 

            String interpretor = &quot;python&quot;;
            String scriptFile = &quot;test.py&quot;;
            String arguments = &quot;ping&quot;;
            String[] cmd = {interpretor,scriptFile,arguments};
          	
          	try {
                Process p = Runtime.getRuntime().exec(cmd);
                ...
            
**Exception:**

java.io.IOException: Cannot run program "python": error=2, No such file or directory

Any help appreciated.
Thanks

</details>


# 答案1
**得分**: 1

Python运行时在基础镜像`openjdk:8-jdk-alpine`中不存在,您需要在调用Python脚本之前首先安装它。

您可以尝试以下操作:

```Dockerfile
FROM openjdk:8-jdk-alpine
RUN apk add --no-cache python
ARG JAR_FILE=target/*.jar
ARG SCRIPT_FILE=src/main/resources/script/test.py
COPY ${JAR_FILE} app.jar
COPY ${SCRIPT_FILE} test.py
ENTRYPOINT ["java","-jar","/app.jar"]
英文:

Python runtime does not exist in the base image openjdk:8-jdk-alpine, you need to install it first before calling python script.

You can try below

FROM openjdk:8-jdk-alpine
RUN apk add --no-cache python
ARG JAR_FILE=target/*.jar
ARG SCRIPT_FILE=src/main/resources/script/test.py
COPY ${JAR_FILE} app.jar
COPY ${SCRIPT_FILE} test.py
ENTRYPOINT [&quot;java&quot;,&quot;-jar&quot;,&quot;/app.jar&quot;]

huangapple
  • 本文由 发表于 2020年7月22日 15:58:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/63029486.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定