如何将 Unix 命令输出传递给 Python 函数

How to pass an Unix command output to Python function

我有一个要求,我需要在本地计算机上 运行 一个 docker 命令并将此列表发送到远程服务器并检查这些图像是否存在。我需要将远程服务器上不存在的图像列表重新 运行 到本地服务器。我需要用 python 来完成。我通过混合 shell 和 python 编写了一些代码,如下所示。

List=$(docker images -q | grep "docker pull" | awk '{print }') #this command is mandatory to get exact docker name.
fab remote_sync_system_spec_docker_to_aws_artifactory:List -u ${USERNAME} -H 1.2.3.4

我正在尝试传递 shell 命令的输出,即通过 fab 列表到 pyhon 函数,因为 above.That 函数如下所示。

def remote_sync_system_spec_docker_to_aws_artifactory(List):
for line in List:
if( os.popen("docker images -q $line") == none )
List=... #need to prepare list and return back to calling function.

一旦我在远程服务器上获得列表,我需要return将它返回到调用函数,我可以在那里做一些操作。基本上我可以使用 shell 但问题是在我的项目中不接受使用 sshpass 连接到远程服务器所以寻找 python 脚本。

os.popen()

将return和内存中的对象,你应该做的是

def remote_sync_system_spec_docker_to_aws_artifactory(List):
    for line in List:
        if( os.popen("docker images -q $line").read() == none ):
            List=... #need to prepare list and return back to calling function.

如果您只需要从 shell 命令获取输出,您应该避免使用 os.popen() 甚至它的替代品 subprocess.Popen()

对于最近的 Python 3.x,使用 subprocess.run():

import subprocess

List = ()
for result in subprocess.run(["docker", "images", "-q"],
        stdout=subprocess.PIPE, universal_newlines=True).stdout.split('\n'):
    if 'docker pull' in result:
        List.append(result.split()[3])

在Python 2.x中对应的函数是subprocess.check_output().

也许您会想用更专注的东西替换 grep'docker pull' in result 将在行中的任何位置查找字符串,但您可能希望将其限制在特定的列中,例如。

作为传输列表的简单方法,我建议使用管道而不是变量。

docker images -q | awk '/docker pull/ { print  }' |
fab remote_sync_system_spec_docker_to_aws_artifactory_stdin -u ${USERNAME} -H 1.2.3.4

其中函数类似于

import sys, subprocess

def remote_sync_system_spec_docker_to_aws_artifactory_stdin (handle=sys.stdin):
    """
    Read Docker image identifiers from file handle; check which
    ones are available here, and filter those out; return the rest.
    """
    missing = ()
    for line in handle:
        repo = line.rstrip('\n')
        if subprocess.run(['docker', 'images', '-q', repo],
                stdout=subprocess.PIPE, universal_newlines=True).stdout == "":
            missing.append(repo)
    return missing