[英]python fabric run command return error as stdout
我使用結構運行在另一台主機上執行命令,並且我想捕捉執行命令的標准錯誤。 像這樣的結構代碼:
def remoteTask(logfile):
with settings(warn_only=True):
result = run("tail -n4 %s | grep \'[error]\' | awk \'{print $1,$2,$0}\'" % logfile)
if result.failed:
raise Exception("Tail failed")
else:
sys.stdout.write(result)
當尾部失敗時,result.failed為false,結果的值為stderr of tail。 而且面料不會拋出異常。
$ python exec.py
stdout: tail: cannot open `/var/log/test.log' for reading: No such file or directory
我只是想從結構中退出或警告,以了解我的腳本是否成功,但是在這種情況下,我無法捕獲。
由於管道和paramiko的工作方式,結構僅返回管道鏈中最后一個命令的結果代碼。 在這種情況下, awk
命令返回0(或success == True
)。 如果您願意,可以與其他結構一起解決此問題:
from fabric.contrib import files
def remoteTask(logfile):
if not files.exists(logfile):
raise Exception('%s does not exist!' % logfile)
with settings(warn_only=True):
result = run("tail -n4 %s | grep \'[error]\' | awk \'{print $1,$2,$0}\'" % logfile)
有關為什么這樣做的更多信息,您可以在此處閱讀有關管道的更多信息: http : //www.gnu.org/software/bash/manual/html_node/Pipelines.html
您也可以只運行您擁有的命令
set -o pipefail
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.