英文:
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 ["java","-jar","/app.jar"]
Now my App has a line of code which executes a python script, something like this :
Code snippet :
String interpretor = "python";
String scriptFile = "test.py";
String arguments = "ping";
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 ["java","-jar","/app.jar"]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论