如何使用 Python 捕获 subprocess.call 错误?

cbl*_*bll 4 python subprocess docker

我正在尝试下载特定的 Docker 映像,用户将在其中输入版本。但是,如果版本不存在,Docker 将抛出错误。

我正在使用subprocess.call管道从 Python 3 连接到终端。

示例代码:

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)])
Run Code Online (Sandbox Code Playgroud)

如果未找到版本,docker 将在终端中输出:

docker: Error response from daemon: manifest for user/software:8712378 not found.
Run Code Online (Sandbox Code Playgroud)

如何在 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?`
Run Code Online (Sandbox Code Playgroud)

Eri*_*ouf 7

如果您对程序将其输出写入stderr并没有直接与之交互感到满意,那么执行您所要求的最简单方法是使用check_call而不是call. check_call如果它正在运行的命令退出时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")
Run Code Online (Sandbox Code Playgroud)


小智 5

您可以使用Popen函数subprocess来获取stderr和蟒蛇控制台打印,如文档说,对subprocess.call

注意 请勿将 stdout=PIPE 或 stderr=PIPE 与此函数一起使用,因为这可能会根据子进程输出量造成死锁。当您需要管道时,将 Popen 与communication() 方法一起使用。

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")
Run Code Online (Sandbox Code Playgroud)