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

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

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

问题

Dockerfile:

  1. FROM openjdk:8-jdk-alpine
  2. ARG JAR_FILE=target/*.jar
  3. ARG SCRIPT_FILE=src/main/resources/script/test.py
  4. COPY ${JAR_FILE} app.jar
  5. COPY ${SCRIPT_FILE} test.py
  6. ENTRYPOINT ["java","-jar","/app.jar"]

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

  1. String interpretor = "python";
  2. String scriptFile = "test.py";
  3. String arguments = "ping";
  4. String[] cmd = {interpretor,scriptFile,arguments};
  5. try {
  6. Process p = Runtime.getRuntime().exec(cmd);
  7. ...
  8. }
  9. **异常**

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

  1. 任何帮助都会感激。谢谢。
  2. <details>
  3. <summary>英文:</summary>
  4. i am new to docker and trying to dockerize a java app, which in turn calls a python script
  5. Dockerfile :
  6. FROM openjdk:8-jdk-alpine
  7. ARG JAR_FILE=target/*.jar
  8. ARG SCRIPT_FILE=src/main/resources/script/test.py
  9. COPY ${JAR_FILE} app.jar
  10. COPY ${SCRIPT_FILE} test.py
  11. ENTRYPOINT [&quot;java&quot;,&quot;-jar&quot;,&quot;/app.jar&quot;]
  12. Now my App has a line of code which executes a python script, something like this :
  13. Code snippet :
  14. String interpretor = &quot;python&quot;;
  15. String scriptFile = &quot;test.py&quot;;
  16. String arguments = &quot;ping&quot;;
  17. String[] cmd = {interpretor,scriptFile,arguments};
  18. try {
  19. Process p = Runtime.getRuntime().exec(cmd);
  20. ...
  21. **Exception:**

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

  1. Any help appreciated.
  2. Thanks
  3. </details>
  4. # 答案1
  5. **得分**: 1
  6. Python运行时在基础镜像`openjdk:8-jdk-alpine`中不存在,您需要在调用Python脚本之前首先安装它。
  7. 您可以尝试以下操作:
  8. ```Dockerfile
  9. FROM openjdk:8-jdk-alpine
  10. RUN apk add --no-cache python
  11. ARG JAR_FILE=target/*.jar
  12. ARG SCRIPT_FILE=src/main/resources/script/test.py
  13. COPY ${JAR_FILE} app.jar
  14. COPY ${SCRIPT_FILE} test.py
  15. 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

  1. FROM openjdk:8-jdk-alpine
  2. RUN apk add --no-cache python
  3. ARG JAR_FILE=target/*.jar
  4. ARG SCRIPT_FILE=src/main/resources/script/test.py
  5. COPY ${JAR_FILE} app.jar
  6. COPY ${SCRIPT_FILE} test.py
  7. 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:

确定