Python:使用Fabric run命令将输出保存到变量

Python:使用Fabric run命令将输出保存到变量,python,fabric,Python,Fabric,我在Mac OS X上使用Python 2.7 with Fabric。最近我注意到,当我的SSH连接到的主机上没有主目录时,我的脚本错误地保存了nodename变量。这是因为当我登录到该主机时会显示一个错误,它会将该错误和run('whatevercommand')保存到该变量中。例如,在以下命令中: def saveHostname(): with settings( hide('running', 'warnings'), shell='/bin

我在Mac OS X上使用Python 2.7 with Fabric。最近我注意到,当我的SSH连接到的主机上没有主目录时,我的脚本错误地保存了nodename变量。这是因为当我登录到该主机时会显示一个错误,它会将该错误和run('whatevercommand')保存到该变量中。例如,在以下命令中:

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
它将“节点名”保存为:


在使用Python run命令时,是否可以忽略错误而不将其保存到变量中?

忽略错误的一种方法是在将run('hostname-s')的输出存储到nodename之前测试它

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

但对于出现此错误的主机,我仍然无法仅存储节点名并完成其他函数的脚本。如果希望成功检索实际主机名,则需要在主机上修复此错误。
with hide('output'):
    temp = run('hostname -s') 
    if "Could not chdir" not in temp:
         nodename = temp
         print nodename
    else:
         nodename = None