如何检查Docker实例是否正在运行? [英] How to check if a docker instance is running?

查看:556
本文介绍了如何检查Docker实例是否正在运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python启动docker实例。

I am using Python to start docker instances.

如何确定它们是否正在运行?我可以很容易地从终端使用 docker ps ,例如:

How can I identify if they are running? I can pretty easily use docker ps from terminal like:

docker ps | grep myimagename

,如果返回任何内容,则映像正在运行。如果返回空字符串,则图像未运行。

and if this returns anything, the image is running. If it returns an empty string, the image is not running.

但是,我不明白如何获取 subprocess.Popen 可以使用它-它需要一个 arguments 列表,例如:

However, I cannot understand how to get subprocess.Popen to work with this - it requires a list of arguments so something like:

    p = subprocess.Popen(['docker', 'ps', '|', 'grep', 'myimagename'], stdout=subprocess.PIPE)
    print p.stdout

不起作用,因为它尝试采用 docker ps并将其设置为 docker和 ps命令(docker不支持)。

does not work because it tries to take the "docker ps" and make it "docker" and "ps" commands (which docker doesn't support).

似乎也无法给出完整的命令,因为 Popen 试图运行 entire 第一个参数作为可执行文件,因此失败了:

It doesn't seem I can give it the full command, either, as Popen tries to run the entire first argument as the executable, so this fails:

    p = subprocess.Popen('docker ps | grep myimagename', stdout=subprocess.PIPE)
    print p.stdout

有没有一种方法可以从Python实际运行 docker ps ?我不知道尝试使用 subprocess 是否是最佳途径。但是,这正是我用来运行docker容器的方式。

Is there a way to actually run docker ps from Python? I don't know if trying to use subprocess is the best route or not. It is what I am using to run the docker containers, however, so it seemed to be the right path.


  • 如何确定是否一个docker实例正在从Python脚本运行?

推荐答案

一种选择是使用 subprocess.check_output 设置 shell = True (感谢slezica!):

One option is to use subprocess.check_output setting shell=True (thanks slezica!):

s = subprocess.check_output('docker ps', shell=True)
print 'Results of docker ps' + s

如果 docker ps 命令失败(例如,您不启动docker-machine)然后 check_output 会引发异常。

if the docker ps command fails (for example you don't start your docker-machine) then check_output will throw an exception.

一个简单的查找便可以验证您的容器是否已找到:

A simple find can then verify your container is found / not-found:

if s.find('containername') != -1:
    print 'found!'
else:
    print 'not found.'

我建议使用容器哈希ID而不是容器 name 也一样,因为该名称可能会在 docker ps 的映像名称或其他结果中重复。

I would recommend using the container hash id and not container name in this case, too, as the name may be duplicated in the image name or other results of the docker ps.

这篇关于如何检查Docker实例是否正在运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆