【问题标题】:Need to run docker run command inside python script需要在 python 脚本中运行 docker run 命令
【发布时间】:2017-07-01 14:34:59
【问题描述】:

我的 Docker 命令是:

docker run --rm wappalyzer/cli https://wappalyzer.com

当我运行我的 python 脚本时:

#!/usr/bin/python
from subprocess import call
import json
import os
import docker

docker run --rm wappalyzer/cli "MYURL"

它说

File "t.py", line 7
    docker run --rm wappalyzer/cli "MYURL"
             ^
SyntaxError: invalid syntax

我的操作系统是 ubuntu 14.04,我正在使用 ubuntu 终端。

【问题讨论】:

  • 也许你应该看看os.system()subprocess.checkoutput(),只是将你的命令行粘贴到程序中,即使不引用它也行不通。

标签: python docker


【解决方案1】:

正如@AndyShinn 所说,Python 不是 shell 语言,但您可以像运行 shell 命令一样调用 docker:

#!/usr/bin/python
import subprocess

with open("/tmp/output.log", "a") as output:
    subprocess.call("docker run --rm wappalyzer/cli https://wappalyzer.com", shell=True, stdout=output, stderr=output)

使用这种方法,您不需要导入 docker。

【讨论】:

  • 我需要将上述命令重定向到文本文件而不是在终端中显示。请你帮我解决这个问题。我是 Ubuntu 和 python 的新手。
  • 我已经添加了文件输出。
  • 不客气:link
【解决方案2】:

this answer 的极端情况和参数化如下。

最好使用subprocess.run 而不是subprocess.call

import docker
import subprocess
import os
import time


def main():
    client, log_path = _set_up_environment()
    _run_docker_compose("docker-compose-with-rabbit.yaml", log_path)


def _run_docker_compose(docker_compose_name, log_path):
    bash_command = f"docker-compose -f {docker_compose_name}} up -d"
    _execute_shell_command(bash_command, log_path)


def _execute_shell_command(bash_command, log_path):
    with open(log_path, "w") as output:
        subprocess.run(
            bash_command,
            shell=True,  # pass single string to shell, let it handle.
            stdout=output,
            stderr=output
        )
    while not output.closed:
        time.sleep(0.1)
    print(f"{os.linesep} COMMAND {bash_command} LOG OUTPUT:")
    with open(log_path, "r") as output:
        for line in output:
            print(line)


def _create_docker_log_file():
    log_location, log_name = "logs", "output.log"
    log_path = os.path.join(os.getcwd(), log_location, log_name)
    os.makedirs(os.path.dirname(log_path), exist_ok=True)
    assert os.path.isdir(os.path.dirname(log_path))
    if not os.path.isfile(log_path):
        os.mknod(log_path)

    return log_location, log_name, log_path


def _set_up_environment():
    log_location, log_name, log_path = _create_docker_log_file()
    client = docker.from_env()
    return client, log_path

if __name__ == "__main__":
    main()


【讨论】:

    【解决方案3】:

    这不是有效的 Python 代码。如果您只是想运行一个容器并将命令作为参数传递,您可以执行以下操作:

    #!/usr/bin/env python
    import sys
    import docker
    
    image = "wappalyzer/cli"
    
    client = docker.from_env()
    client.containers.run(image,  sys.argv[1], True)
    

    但是,如果这是您所追求的,您应该阅读有关 Python 和从 Python 运行进程的更多信息。 Python 不是一种 shell 语言,你不能只使用内联的 shell 命令。

    【讨论】:

      【解决方案4】:

      更新:2022-03-22

      我们现在有python-on-whales Python 的 Docker 客户端。适用于 Python 3.7 及更高版本的 Linux、macOS 和 Windows。

      >>> from python_on_whales import docker
      >>> output = docker.run("hello-world")
      >>> print(output)
      Hello from Docker! This message shows that your installation appears to be 
      working correctly.
      >>> from python_on_whales import DockerClient
      >>> docker = DockerClient(compose_files=["./my-compose-file.yml"])
      >>> docker.compose.build()
      >>> docker.compose.up()
      ...
      >>> docker.compose.down()
      

      【讨论】:

      【解决方案5】:

      您可以使用名为docker 的 pip 包并使用它连接到 Docker。 在 subProcess 中运行命令和此解决方案之间的区别在于格式。您可以管理您的图像、容器以及 CLI 能够执行的所有操作。

      在这里查看:https://docker-py.readthedocs.io/en/stable/

      示例:

      import docker
      client = docker.from_env()
      
      client.containers.run("ubuntu", "echo hello world")
      
      # or
      
      client.containers.run("bfirsh/reticulate-splines", detach=True)
      
      # you can even stream your output like this:
      for line in container.logs(stream=True):
         print(line.strip())
      
      

      所有代码示例都可以在我提到的源 URL 中找到。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-08-31
        • 2020-12-31
        • 2019-05-28
        • 2019-06-11
        • 2023-01-19
        • 2020-02-02
        • 1970-01-01
        相关资源
        最近更新 更多