Python:我的try / except块总是返回True

时间:2016-03-24 18:41:51

标签: python python-2.7

如果我在独立脚本中单独运行_create_system_cobbler函数,我就能捕获错误。在这种情况下,我正在模拟一个错误,它会告诉我我正在使用的DNS名称已经存在。但是,如果我将其放入函数并从main函数进行调用,则它始终返回True。我

错误:

Error! <class 'cobbler.cexceptions.CX'>:'dns-name duplicated: inadmin001.domain.local'

_create_system_cobbler function

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()

1 个答案:

答案 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)