簡體   English   中英

通過 docker-py 使用管道

[英]Using pipes with docker-py

https://github.com/docker/docker-py的示例中,它們將命令的結果返回到 docker 映像,如下所示:

>>> client.containers.run("ubuntu:latest", "echo hello world")
'hello world\n'

我想要的是使用 pipe - 例如,如果我能這樣做會很棒:

>>> client.containers.run("ubuntu:latest", "echo hello world | wc")
'       1       2      12\n'

但是,相反,我得到了這個:

 >>> client.containers.run("ubuntu:latest", "echo hello world | wc")
    b'hello world | wc\n'

在 docker 中運行兩個命令的最簡單方法是什么?

每當您使用 shell 構造,例如$ENV_VAR| 等,確保您實際上有一個 shell 來解釋它們,否則它們將具有它們的字面值,要了解您的調用為什么缺少外殼,您必須了解 docker ENTRYPOINTCMD

如果您查看ubuntu:latest的 dockerfile,您會發現它是

FROM scratch

而且該文件沒有設置ENTRYPOINT ,只有CMD 閱讀CMD 和 Dockerfile 中的 ENTRYPOINT 有什么區別? 有關差異的一些好看的信息。 可以說,在您的情況下,圖像名稱之后的所有內容都替換了cmd

containers.run()的文檔說command可以是strlist 由此,根據觀察到的行為,我們可以推斷命令字符串將在空白處拆分,以創建 arguments 列表,用於 docker exec。

所以,簡而言之,答案是因為| 是 shell 構造,但您沒有執行 shell。 有幾種方法可以將 shell 添加到等式中。 最明顯的是直接運行shell:

>>> client.containers.run("ubuntu:latest", "bash -c 'echo hello world | wc'",)
'      1       2      12\n'

但是您也可以將入口點設置為 shell,這通常在通用容器中完成(但請注意,您仍然必須確保提供-c ,並且必須像以前一樣引用整個 shell 命令。入口點僅提供可執行文件,而不是任何參數)。

>>> client.containers.run("ubuntu:latest", "-c 'echo hello world | wc'", entrypoint="bash")
'      1       2      12\n'

命令行使用標准輸入字段分隔符執行相同的操作:

$ docker run --rm -it ubuntu:latest echo hello world \| wc
hello world | wc

如果我們引用整個內容,我們會破壞輸入字段分隔符周圍的自動拆分:

$ docker run --rm -it ubuntu:latest "echo hello world \| wc"
docker: Error response from daemon: OCI runtime create failed: container_linux.go:345: starting container process caused "exec: \"echo hello world \\\\| wc\": executable file not found in $PATH": unknown.

python 等效項是:

>>> client.containers.run("ubuntu:latest",["echo hello world \\|"])
Traceback (most recent call last):
  [... traceback omitted for brevity ...]
docker.errors.APIError: 500 Server Error: Internal Server Error ("OCI runtime create failed: container_linux.go:345: starting container process caused "exec: \"echo hello world \\\\|\": executable file not found in $PATH": unknown")

很簡單:

client.containers.run("ubuntu:latest", "sh -c 'echo hello world | wc'")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM