如何捕捉与Python的subprocess.call错误?
我试图下载一个特定的Docker镜像,用户将在其中input一个版本。 但是,如果版本不存在,Docker将会抛出一个错误。
我使用subprocess.call
从Python 3pipe道到terminal。
示例代码:
from subprocess import call containerName = input("Enter Docker container name: ") swVersion = input("Enter software version: ") call(["docker", "run", "--name", "{}".format(containerName), "--detach", "--publish", "8080:8080", "user/software:{}".format(swVersion)])
如果找不到版本,docker将在terminal输出:
docker: Error response from daemon: manifest for user/software:8712378 not found.
如何在Python脚本中捕获这个错误?
有些东西是:
try: call(["docker", "run", "--name", "{}".format(containerName), "--detach", "--publish", "8080:8080", "user/software:{}".format(swVersion)]) except: # How do I catch the piped response code here?`
您可以使用subprocess
Popen
函数来获取stderr
并在Python控制台中进行打印,正如文档中对subprocess.call
所说的那样
注意不要对此函数使用stdout = PIPE或stderr = PIPE,因为它可能会根据subprocess输出量死锁。 在需要pipe道时,使用Popen和communications()方法。
proc = subprocess.Popen(["docker", "run", "--name", "{}".format(containerName), "--detach", "--publish", "8080:8080", "user/software:{}".format(swVersion)],stdout=subprocess.PIPE, stderr=subprocess.PIPE, creationflags=subprocess_flags) proc.wait() (stdout, stderr) = proc.communicate() if proc.returncode != 0: print(stderr) else: print("success")
如果程序将其输出写入stderr
并且不直接与它进行交互,则最简单的方法就是使用check_call
而不是call
。 check_call
会引发exception,如果运行的命令以0
以外的任何0
作为状态退出。
try: check_call(["docker", "run", "--name", "{}".format(containerName), "--detach", "--publish", "8080:8080", "user/software:{}".format(swVersion)]) except CalledProcessError: print("That command didn't work, try again")
- 如何传递本地文件的文件path对于通过Jenkins Job在Selenium Grid Docker上运行的Selenium Web Automation
- Docker-compose推荐使用数据容器的方式
- Docker Swarm的文件存储
- 在重新启动后,群集节点不能重新joinDocker群中的群集
- Docker – Nodejs到Mongodb连接工作,但收集为空
- 我如何从Docker容器中运行任意的MySQL命令?
- 在zeppelin-server上,Apache-Zeppelin 0.7从源代码生成失败
- 单一docker集装箱在CPU性能上略胜过其主机:为什么?
- Mkbundle单声道程序集绑定redirect