Skip to main content
 首页 » 编程设计

python之仅调用 python 返回代码状态

2025年05月04日77exmyth

我在 python 中有以下代码:

i = call(["salt-cloud", "-m", fileName, "--assume-yes"]) 
print (i) 

i 始终为 0,因为操作已完成。

问题是我想得到这个操作的输出。在我们的例子中:

window: 
    ---------- 
    Error: 
        ---------- 
        Not Deployed: 
            Failed to start Salt on host window 

是运行salt-cloud -m fileName --assume-yes的输出,表示在这个过程中出现了错误,我想知道。

如何在 Python 中实现它?

请您参考如下方法:

使用 check_output 并捕获一个 CalledProcessError ,它将在任何非零退出状态时引发:

from subprocess import check_output, CalledProcessError     
 
try: 
    out = check_call(["salt-cloud", "-m", fileName, "--assume-yes"])  
    print(out)    
except CalledProcessError as e: 
    print(e.message) 

如果您使用的是 python < 2.7,则需要 Popen,check_call 和 check_output 是在 python 2.7 中添加的:

from subprocess import Popen, PIPE 
 
p = Popen(["salt-cloud", "-m", filename, "--assume-yes"],stderr=PIPE,stdout=PIPE) 
 
out, err = p.communicate() 
 
print( err if err else out)