2016-11-14 70 views
0

我使用fabric運行在另一個主機上執行命令,我想趕上執行命令的stderr。 織物這樣的代碼:python結構運行命令返回錯誤作爲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是假的,並且結果的值是標準錯誤尾巴。面料不會拋出異常。

$ python exec.py 
stdout: tail: cannot open `/var/log/test.log' for reading: No such file or directory 

我只是想從面料得到終止執行或警告知道我的腳本失敗與否,但在這種情況下,我不能趕上。

+0

請確保將你的代碼包含在問題主體中,而不僅僅是通過截圖。 – 2ps

+0

非常感謝您爲我編輯問題主體。下次我會更清楚地說明我的問題!謝謝! –

回答

0

由於管道和paramiko的工作方式,fabric僅返回管道鏈中最後一個命令的結果代碼。在這種情況下,awk命令返回0(或成功== 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

可以ALO只運行你的命令

set -o pipefail 
+0

謝謝你的回答!它幫助我很多! –