我在Mac OS X上使用带有Fabric的Python 2.7。我最近注意到,当我在SSH连接的主机上没有主目录时,我的脚本正在保存nodename变量。这是因为当我登录到该主机时会出现错误,它会将该错误和运行(' 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
它将节省" 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 :(得分:0)
忽略错误的一种方法是在将其存储到节点名称之前测试run的输出(' hostname -s')
with hide('output'):
temp = run('hostname -s')
if "Could not chdir" not in temp:
nodename = temp
print nodename
else:
nodename = None