目标和问题
拥有可以持续运行的容器/Pod 部署。容器应执行的命令是:/usr/local/bin/python3
该命令的参数是:"-c $'import time\\nwhile (True):\\n print(\".\");time.sleep(5);'"
。但是,当我执行kubectl apply -f "PATH_TO_THE_KUBERNETES_YAML_FILE"
时部署错误并出现以下 Python 异常:IndentationError: unexpected indent
.
Pod 部署用作调用 Python 代码的媒介,该代码与 Certbot 客户端交互,作为使用 LetsEncrypt 证书时任务的一部分。
查看项目here
所以应该可以部署 Pod >> 执行 kubectl exec ...
进入作为 Kubernetes 部署的一部分运行的容器。
尝试过:
定义 Kubernetes 命令参数行的各种方法。
- 通过 exec Python 选项。例如:
python3 -c exec(\"import time\nwhile True: print(\".\");time.sleep(5);\")
- 用 ` 和 " 的不同组合封装要执行的代码。
-
$'textwrap.dedent("""import time while True: print(".") time.sleep(5)""")'
... 尝试使用:
args: - "-c $'import time\\nwhile (True):\\n print(\".\");time.sleep(5);'"
作为
args: ["-c $'import time\\nwhile (True):\\n print(\".\");time.sleep(5);'"]
的替代品确认 Python 代码本身可以工作。
- 两者均使用
Python3 -c "..."
直接或通过docker run
调用它命令to a container from this Dockerfile - 我已经完成了通常的谷歌搜索、堆栈*搜索等等。我还访问过官方 Kubernetes GitHub 存储库页面并搜索那里的问题。关闭的也好,开放的也好。我还没有看到任何与此相匹配的问题。
- Kubectl 在执行
...apply -f YAML_FILE
时不会提示,关于 YAML 文件的格式以及对 Pod 部署规范的遵守。 - 尝试使用一些 bash 代码:
["/bin/bash", "-ecx", "while :; do printf '.'; sleep 5 ; done"]
<-- 有效。
更多信息
- Python 版本为 v3.7.2
- Kubernetes 版本为 v1.12.5-gke.10
这似乎是在 Kubernetes Pod 部署 YAML 文件中指定 Python 代码的组合……这与 Python 对重要空格和缩进的要求不太相符。正如您在 #tried 部分中所读到的,它在直接调用 Python 或通过 Docker run/exec 命令调用时有效。
如何解决此问题?
最佳答案
所以我能够在 Kubernetes Slack channel 上获得这方面的帮助。这是一个 YAML 语法问题。
Pod 部署 YAML 文件中的以下内容解决了该问题
args:
- |-
-c
import time
while True:
print('.')
time.sleep(5)
这与 Dockerfile 结合使用......
FROM larssb/certbot-dns-cloudflare-python3
LABEL author="https://github.com/larssb"
#
# Container config
#
WORKDIR /letsencryptit
#
# COPY IN DATA
#
COPY ./scripts /scripts/
COPY ./letsencryptit /letsencryptit/
#
# INSTALL
#
RUN pip install --upgrade google-api-python-client --disable-pip-version-check --no-cache-dir \
&& pip install --upgrade oauth2client --disable-pip-version-check --no-cache-dir \
&& pip install --upgrade sty --disable-pip-version-check --no-cache-dir \
&& chmod +x /scripts/deploy-hook-runner.sh
# Set an ENTRYPOINT to override the entrypoint specified in certbot/certbot
ENTRYPOINT ["/usr/local/bin/python3"]
CMD ["-c"]
ENTRYPOINT
,因为 Pod 部署会重复使用它。但是,Dockerfile 的 CMD
会被 Pod 部署 YAML 文件中的 args
属性覆盖。
args属性详细解释
-c
是 Python 二进制文件的参数- 其余的都是标准的。 Python 代码,让通过 Pod 部署部署的容器持续运行,以便它可以随时通过
kubectl exec
对它进行命令调用
关键
args
属性的这一部分 > - |-
。它会去除换行符和任何尾随空白行。使得声明多行 Python 代码块成为可能
文档
- 要点,其中包含有关
args
属性中所需语法的示例代码。找到它here . - Dockerfile使用过
- Kubernetes Pod 部署 YAML 文件。看看here
- On the YAML "strip" syntax
感谢@wizzwizz4、@a_guest 的评论和建议。他们帮助我解决了这个问题,缩小了解决方案的范围。 另外,非常感谢 Kubernetes Slack channel 上的 @grampelberg 先生为我提供的帮助和解决方案。
关于python - Python 3 引发的 IndentationError : unexpected indent,。Pod 部署 YAML 中 Kubernetes args 条目中使用的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55463094/