问题描述
我在Mac OS X上将Python 2.7与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
它将“ 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 run命令时,是否会忽略错误并且不将其保存到变量中?
1楼
忽略错误的一种方法是在将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