如何捕捉与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而不是callcheck_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")