2015-12-30 36 views
0

我想直接從Python運行我現有的fabfile任務,而不使用cli。 如何捕獲「執行」異常並捕獲輸出以記錄發生任何異常?如何直接從Python運行Fabric任務來捕獲異常和輸出?

@roles(['localhost']) 
def my_sudo_task(): 
    sudo('ls -l /root/') 

from fabfile import my_sudo_task 
from fabric.tasks import execute 

execute(my_sudo_task) 

這裏是我的確切問題:

try: 
    # is there a way to leave out stderr and capture it somehow? 
    with settings(hide('stdout', 'stderr', 'aborts', 'warnings', 'running')): 
     execute(my_sudo_task) 
except Exception as e: # doesnt catch error 
    print ('ERROR') 
    raise 
except: 
    print ('ERROR') # catches but lacks the error message that i can log 

回答

1

你應該通過檢查裏面的任務的結果代碼處理錯誤。例外情況不足以描述。

from fabric.api import * 

@roles(['localhost']) 
def my_sudo_task(): 
    with settings(warn_only=True): 
     result = sudo('ls -l /root/') 

    if result.return_code == 0: 
     [do something...] 
    elif result.return_code == 1: 
     [do something...] 
    else: 
     [do something else...] 



from fabfile import my_sudo_task 
from fabric.tasks import execute 

execute(my_sudo_task) 

請參閱教程部分failure handling

+0

所有我需要的是執行(任務)來觸發任何異常,當須藤(「不是一個有效的CMD」)失敗。工廠的存在方式1.肯定有比重寫每個任務「提高」更好的方法。 – jayshilling

+0

從文檔:「但是,Fabric默認爲」fail-fast「行爲模式:如果出現任何問題,例如返回非零返回值的遠程程序或您的fabfile的Python代碼遇到異常,執行將立即停止。 – jumbopap

+0

我澄清了這個問題,「除了異常作爲e'沒有捕獲任何東西,只是'除了'工作,但是沒用,因爲它不提供錯誤消息記錄 – jayshilling

0

下解決了我的問題

try: 
    with settings(hide('stdout', 'stderr', 'aborts', 'warnings', 'running')): 
     execute(my_sudo_task) 
except SystemExit as e: 
    print (e.message) 

,因爲 '執行' 在技術上不拋出異常

issubclass(SystemExit, Exception) = False 
0

的NetworkError和的CommandTimeout的例外是fabric.exceptions模塊中定義。 execute()調用返回一個字典,其中包含以主機名作爲關鍵字執行的任務返回的任何內容。如果遇到異常,它也會存儲在字典中。您可以檢查異常的「消息」屬性以獲取問題的字符串描述。請看下面的例子:

>>> from fabric.api import run, execute 
>>> from fabric.context_managers import quiet 
>>> from fabric.state import env 
>>> env.skip_bad_hosts = True 
>>> env.warn_only = True 
>>> def task_a(): 
... return run('pwd') 
... 
>>> with quiet(): 
... a = execute(task_a,hosts=['badhost']) 
... 
>>> a 
{'badhost': NetworkError(Name lookup failed for badhost) => gaierror(8, 'nodename nor servname provided, or not known')} 
>>> type(a['badhost']) 
<class 'fabric.exceptions.NetworkError'> 
>>> a['badhost'].message 
'Name lookup failed for badhost'