2017-02-09 191 views
0

我在Mac OS X上使用Python 2.7與Fabric。我最近注意到,當我沒有主目錄時,我的腳本不正確地保存了nodename的變量我SSH進入的主機。這是因爲當我登錄到該主機時會出現錯誤,並且會將該錯誤和運行('whatevercommand')保存到該變量中。例如,在下面的命令:Python:使用Fabric運行命令將輸出保存到變量

def saveHostname(): 
    with settings( 
     hide('running', 'warnings'), 
     shell='/bin/bash -c'): 

     date = run ('date') 
     host_type = run ('uname') 
     if "Linux" in host_type: 
      with hide('output'): 
       nodename = run('hostname -s') 
       print nodename 

這將節省「節點名稱」爲:

Could not chdir to home directory /home/yourdirectory/: No such file or directory (This is the error I get everytime I log into the machine) 

hostname (This is the hostname of the host I am logging into with Python) 

反正是有忽略錯誤和使用Python運行命令時沒有將其保存到一個變量?忽略錯誤

回答

0

一種方法是將其存儲到節點名前試運行的輸出(「主機名-s」)

with hide('output'): 
    temp = run('hostname -s') 
    if "Could not chdir" not in temp: 
     nodename = temp 
     print nodename 
    else: 
     nodename = None 
+0

但對於那些有此錯誤的主機,我仍然無法只存儲節點名並將我的腳本完成到我的其他功能 – user5578188

+0

然後,如果要成功檢索實際主機名,則需要修復主機上的錯誤。 –