如果我在独立脚本中单独运行_create_system_cobbler
函数,我就能捕获错误。在这种情况下,我正在模拟一个错误,它会告诉我我正在使用的DNS名称已经存在。但是,如果我将其放入函数并从main
函数进行调用,则它始终返回True
。我
Error! <class 'cobbler.cexceptions.CX'>:'dns-name duplicated: inadmin001.domain.local'
def _create_system_cobbler():
try:
cobbler_server = xmlrpclib.Server("https://127.0.0.1/cobbler_api")
except socket.error:
print "Can't Connect to Cobbler"
quit()
serverinfo = {
'hostname' : 'inadmin001',
'macaddress': '00:2e:4e:78:ba:86',
'ipaddress': '172.21.10.33',
'dnsname': 'inadmin001.domain.local'
}
try:
token = cobbler_server.login("cobbler","cobbler")
system_id = cobbler_server.new_system(token)
...
<more code>
...
except xmlrpclib.Fault as err:
errormsg = "Error " + str(err.faultString)
return False, errormsg
return True, serverinfo
def main(session)
handler, serverinfo = _create_system_cobbler()
if handler:
print "Let's create a VM"
print serverinfo
# Let's continue with the rest of the code
else:
print serverinfo
quit()
答案 0 :(得分:0)
使用返回代码不是非常pythonic,你应该编写函数假设一切顺利,外面有except
例外:
def create_system_cobbler():
cobbler_server = xmlrpclib.Server("https://127.0.0.1/cobbler_api")
serverinfo = {
'hostname' : 'inadmin001',
'macaddress': '00:2e:4e:78:ba:86',
'ipaddress': '172.21.10.33',
'dnsname': 'inadmin001.domain.local'
}
token = cobbler_server.login("cobbler","cobbler")
system_id = cobbler_server.new_system(token)
...
<more code>
...
return cobbler_server
def main(session):
try:
handler = create_system_cobbler()
except socket.error:
print("Can't Connect to Cobbler")
except xmlrpclib.Fault as err:
print('Error: ', err)