Python与类的执行顺序

时间:2017-08-07 20:45:08

标签: python python-2.7

我试图理解Python2.7.10在我的脚本中的行为方式。

这就是我所拥有的:

import sys, getopt
import socket
import re
import pprint

class New_VM(object):
    ''' Class to validate options and arguments being passed in. '''
    def __init__(self, argv):
        # Accept command line options and arguments being passed in to the script.
        # Options are being held in the opts data structure.
        # Arguments are being held in the args data structure.
        try:
            opts, args = getopt.getopt(argv, "hn:m:p:d:s:r:t:",["hostname=","eth0=","eth1=","defaultgw=","subnet=","route-eth0=", "rt_tables="])
            #pprint.pprint(opts)
            print(opts[0])
            #sys.exit(2)
        # Raise exception and die if invalid option is passed in.
        except getopt.GetoptError:
            print 'Invalid script syntax:'
            print 'buildNetworkFile.py -n <hostname> -m <eth0_ip> -p <eth1_ip> -d <default_gw> -s <subnet> -r <route-eth0 file> -t <rt_tables file>'
            sys.exit(2)


        # Validate correct number of options/arguments are being passed in and take action accordingly.
        for opt, arg in opts:
            # Display help if -h option is passed or die if less than 5 options passed.
            if opt == '-h' or len(opts) < 5:
            #if opt == '-h':
                print 'Please use syntax below to run script.'
                print 'Script requires 5 arguments to be passed in.'
                print 'buildNetworkFile.py -n <hostname> -m <eth0_ip> -p <eth1_ip> -d <default_gw> -s <subnet> -r <route-eth0 file> -t <rt_tables file>'
                sys.exit(2)
                #break
            # Catch the hostname being passed in.
            elif opt in ("-n", "--hostname"):
                    self._hostname = arg
            # Validate management IP being passed in.
            elif opt in ("-m", "--eth0"):
                try:
                    self._eth0 = arg
                    socket.inet_pton(socket.AF_INET, self._eth0)
                except AttributeError:
                    try: 
                        self._eth0 = arg
                        socket.inet_aton(self._eth0)
                    except socket.error:
                        print 'Socket error when validating management(eth0) IP..' 
                        #return False
                except socket.error:
                        print 'Invalid managment(eth0) IP. Please check your IP and try again.'
                        sys.exit(2)
            # Validate public IP being passed in.
            elif opt in ("-p", "--eth1"):
                try:
                    self._eth1 = arg
                    socket.inet_pton(socket.AF_INET, self._eth1)
                except AttributeError:
                    try: 
                        self._eth1 = arg
                        socket.inet_aton(self._eth1)
                    except socket.error:
                        print 'Socket error when validating public(eht1) IP..' 
                        #return False
                except socket.error:
                        print 'Invalid public(eth1) IP. Please check your IP and try again.'
                        sys.exit(2)
            # Validate default gateway IP being passed in.
            elif opt in ("-d", "--defaultgw"):
                try:
                    self._dg = arg
                    socket.inet_pton(socket.AF_INET, self._dg)
                except AttributeError:
                    try: 
                        self._dg = arg
                        socket.inet_aton(self._dg)
                    except socket.error:
                        print 'Socket error when validating defautl gateway IP..' 
                        #return False
                except socket.error:
                        print 'Invalid Default Gateway IP. Please check your IP and try again.'
                        sys.exit(2)
            elif opt in ("-s", "--subnet"):
            # Validate subnet IP being passed in.
                try:
                    self._subnet = arg
                    socket.inet_pton(socket.AF_INET, self._subnet)
                except AttributeError:
                    try: 
                        self._subnet = arg
                        socket.inet_aton(self._subnet)
                    except socket.error:
                        print 'Socket error when validating subnet IP..' 
                        #return False
                except socket.error:
                        print 'Invalid Subnet IP. Please check your IP and try again.'
                        sys.exit(2)
            # Check if route-eth0 file is being passed in. 
            elif opt in ("-r", "--route-eth0"):
                self._routeEth0 = arg
                try:
                    with open(self._routeEth0) as text_file:
                        with open('routeEth0.txt', mode='w') as out_file:
                            lines = text_file.readlines()
                            out_file.writelines(lines)
                except:
                    print('The route-eth0 file you specified was not found. Please try again.\n')
                    sys.exit(2)
            # Check if rt_tables file is being passed in.
            elif opt in ("-t", "--rt_tables"):
                self._rtTables = arg
                try:
                    with open(self._rtTables) as text_file:
                        with open('rt_tables.txt', mode='w') as out_file:
                            lines = text_file.readlines()
                            out_file.writelines(lines)
                except:
                    print('The rt_tables file you specified was not found. Please try again.\n')
                    sys.exit(2)
        # If no arguments are passed die. If opts[0] is equal to the script name (buildNetworkFile.py) then die.
        try:
            arg1 = opts[0]
            sys.exit(2)
        except IndexError as e:
            print 'Not enough arguments passed. Please run script with -h option for syntax information.'
            sys.exit(2)

    def __str__(self):
        return 'New_VM\'s'

    @property
    def hostname(self):
        return self._hostname
    @property
    def managementIP(self):
        return self._eth0
    @property
    def publicIP(self):
        return self._eth1
    @property
    def defaultGW(self):
        return self._dg
    @property
    def subnet(self):
        return self._subnet

class Configure_Files(New_VM):
    #def __init__(self):
    #'''Special Init Class for Configure NewtorkFiles Class'''
    #return None

    @property
    def hostname(self):
    return self._hostname

    # Class vars
    domain = 'blah.net'
    networking = 'yes'
    networking_ipv6 = 'yes'
    nozerconf = 'yes'
    gateway = 'self._dg'
    ipv6_defaultgw='2001:578:15:4801:'
    ipv6_defaultdev='eth1'
    hwaddr=''
    mgtInterface='eth0'
    pubInterface='eth1'
    dns1='1.1.1.1'
    dns2='1.1.1.1'
    mgtDomain='blah2.net'
    onBootYes='yes'
    onBootNo='no'
    userCtlYes='yes'
    userCtlNo='No'
    bootProtocol='static'
    peerDnsYes='yes'
    peerDnsNo='No'
    ipv6InitYes='yes'
    ipv6InitNo='no'
    ipv6Addr='2001:578:115:4820:'
    # Ask user for Management Network IP and validate it.
    mgtNetwork = raw_input("Please enter the Management Network IP.\n")
    try:
        socket.inet_pton(socket.AF_INET, mgtNetwork)
    except AttributeError:
        try:
            socket.inet_aton(mgtNetwork)
        except socket.error:
            print 'Socket error when validating subnet IP..'
    except socket.error:
        print 'Invalid Management Network IP. Please check your IP and try again.'
        sys.exit(2)
    # Ask user for Public Network IP and validate it.
    pubNetwork = raw_input("Please enter the Public Network IP.\n")
    try:
        socket.inet_pton(socket.AF_INET, pubNetwork)
    except AttributeError:
        try:
            socket.inet_aton(pubNetwork)
        except socket.error:
            print 'Socket error when validating subnet IP..'
    except socket.error:
        print 'Invalid Public Network IP. Please check your IP and try again.'
        sys.exit(2)


    @property
    def provisionEth0(self):
        return self._eth0
        #return domain

    def network(self):
        ''' Build the contents for /etc/sysconfig/newtork file '''
    '''print 'HOSTNAME=%s' % self._hostname
    print 'DOMAIN=%s' % Configure_Files.domain
    print 'NETWORKING=%s' % Configure_Files.networking
    print 'NETWORKING_IPV6=%s' % Configure_Files.networking_ipv6
    print 'GATEWAY=%s' % self._dg'''
        dg2 = re.sub('[.]',':', self._dg) # Replacing '.' with ':' so it can be appended to IPV6_DEFAULTGW var
        '''print 'IPV6_DEFAULTGW=%s%s' % (Configure_Files.ipv6_defaultgw, dg2)
    print 'IPV6_DEFAULTDEV=%s' % Configure_Files.ipv6_defaultdev'''
        with open('network.txt', mode='w') as out_file:
        out_file.writelines('HOSTNAME=%s \n' % self._hostname)
        out_file.writelines('DOMAIN=%s \n' % Configure_Files.domain)
        out_file.writelines('NETWORKING=%s \n' % Configure_Files.networking)
        out_file.writelines('NETWORKING_IPV6=%s \n' % Configure_Files.networking_ipv6)
        out_file.writelines('GATEWAY=%s \n' % self._dg)
            out_file.writelines('IPV6_DEFAULTGW=%s%s \n' % (Configure_Files.ipv6_defaultgw, dg2))
        out_file.writelines('IPV6_DEFAULTDEV=%s \n' % Configure_Files.ipv6_defaultdev)

    def eth0Config(self):
        '''Build the contents for /etc/sysconfig/network-scripts/ifcfg-eth0'''
        # Grab the HWADDR from the /etc/sysconfig/network-scripts/ifcfg-eth0 file
        try:
            with open('/etc/sysconfig/network-scripts/ifcfg-eth0') as text_file:
                for line in text_file:
                    try:
                        match = re.search(r'HWADDR=(.*)', line, re.M|re.I)
                        Configure_Files.hwaddr=match.group(1)
                        #print(match.group(1))
                        break
                    except:
                        print('There was no \'HWADDR\' string found in the /etc/syconfig/network-scripts/ifcfg-eth0 file.')
                        print('Setting HWADDR to blank')
                        break
                        #sys.exit(2)
        except IOError as e:
            print ('/etc/sysconfig/network-scripts/ifcfg-eth0 not found: ', e)
            sys.exit(2)
        '''print 'HWADDR=%s' % (Configure_Files.hwaddr)
        print 'NAME=%s' % (Configure_Files.mgtInterface)
        print 'DNS1=%s' % (Configure_Files.dns1)
        print 'DNS2=%s' % (Configure_Files.dns2)
    print 'DOMAIN=%s' % (Configure_Files.mgtDomain)
    print 'ONBOOT=%s' % (Configure_Files.onBootYes)
    print 'USERCTL=%s' % (Configure_Files.userCtlNo)
    print 'BOOTPROTO=%s' % (Configure_Files.bootProtocol)
    print 'PEERDNS=%s' % (Configure_Files.peerDnsNo)
        print 'IPADDR=%s' % (self._eth0)
        print 'NETMASK=%s' % (self.subnet)
        print 'NETWORK=%s' % (Configure_Files.mgtNetwork)
        print 'IPV6INIT=%s' % (Configure_Files.ipv6InitYes)
        print 'GATEWAY=%s' % (self._dg)'''
        ipv6addr2 = re.sub('[.]',':', self._eth0) # Replacing '.' with ':' so it can be appended to IPV6ADDR var
        #print 'IPV6ADDR=%s%s' % (Configure_Files.ipv6Addr, ipv6addr2)
        ifcfg_string = '''check_link_down () {\n return 1;\n}''' 
        with open('ifcfg-eth0.txt', mode='w') as out_file:
            out_file.writelines('HWADDR=%s \n' % Configure_Files.hwaddr)
            out_file.writelines('NAME=%s \n' % Configure_Files.mgtInterface)
            out_file.writelines('DNS1=%s \n' % Configure_Files.dns1)
            out_file.writelines('DNS2=%s \n' % Configure_Files.dns2)
            out_file.writelines('DOMAIN=%s \n' % Configure_Files.mgtDomain)
            out_file.writelines('ONBOOT=%s \n' % Configure_Files.onBootYes)
            out_file.writelines('USERCTL=%s \n' % Configure_Files.userCtlNo)
        out_file.writelines('BOOTPROTO=%s \n' % Configure_Files.bootProtocol)
            out_file.writelines('PEERDNS=%s \n' % Configure_Files.peerDnsNo)
            out_file.writelines('IPADDR=%s \n' % self._eth0)
            out_file.writelines('NETMASK=%s \n' % self.subnet)
            out_file.writelines('NETWORK=%s \n' % Configure_Files.mgtNetwork)
            out_file.writelines('IPV6INIT=%s \n' % Configure_Files.ipv6InitYes)
            out_file.writelines('GATEWAY=%s \n' % self._dg)
            out_file.writelines('IPV6ADDR=%s%s \n' % (Configure_Files.ipv6Addr, ipv6addr2))
            out_file.writelines(ifcfg_string)

    def eth1Config(self):
        '''Build the contents for /etc/sysconfig/network-scripts/ifcfg-eth1'''
        # Grab the HWADDR from the /etc/sysconfig/network-scripts/ifcfg-eth1 file
        try:
            with open('/etc/sysconfig/network-scripts/ifcfg-eth1') as text_file:
                for line in text_file:
                    try:
                        match = re.search(r'HWADDR=(.*)', line, re.M|re.I)
                        Configure_Files.hwaddr=match.group(1)
                        #print(match.group(1))
                        break
                    except:
                        print('There was no \'HWADDR\' string found in the /etc/syconfig/network-scripts/ifcfg-eth1 file.')
                        print('Setting HWADDR to blank')
                        break
                        #sys.exit(2)
        except IOError as e:
                        print ('/etc/sysconfig/network-scripts/ifcfg-eth1 not found: ', e)
                        sys.exit(2)

        '''print 'HWADDR=%s' % (Configure_Files.hwaddr)
        print 'NAME=%s' % (Configure_Files.mgtInterface)
        print 'DNS1=%s' % (Configure_Files.dns1)
        print 'DNS2=%s' % (Configure_Files.dns2)
    print 'DOMAIN=%s' % (Configure_Files.domain)
    print 'ONBOOT=%s' % (Configure_Files.onBootYes)
    print 'USERCTL=%s' % (Configure_Files.userCtlNo)
    print 'BOOTPROTO=%s' % (Configure_Files.bootProtocol)
    print 'PEERDNS=%s' % (Configure_Files.peerDnsNo)
        print 'IPADDR=%s' % (self._eth1)
        print 'NETMASK=%s' % (self.subnet)
        print 'NETWORK=%s' % (Configure_Files.pubNetwork)
        #print 'IPV6INIT=%s' % (Configure_Files.ipv6InitYes)
        print 'GATEWAY=%s' % (self._dg)'''
        ifcfg_string = '''check_link_down () {\n return 1;\n}''' 
        with open('ifcfg-eth1.txt', mode='w') as out_file:
            out_file.writelines('HWADDR=%s \n' % Configure_Files.hwaddr)
            out_file.writelines('NAME=%s \n' % Configure_Files.mgtInterface)
            out_file.writelines('DNS1=%s \n' % Configure_Files.dns1)
            out_file.writelines('DNS2=%s \n' % Configure_Files.dns2)
            out_file.writelines('DOMAIN=%s \n' % Configure_Files.domain)
            out_file.writelines('ONBOOT=%s \n' % Configure_Files.onBootYes)
            out_file.writelines('USERCTL=%s \n' % Configure_Files.userCtlNo)
        out_file.writelines('BOOTPROTO=%s \n' % Configure_Files.bootProtocol)
            out_file.writelines('PEERDNS=%s \n' % Configure_Files.peerDnsNo)
            out_file.writelines('IPADDR=%s \n' % self._eth0)
            out_file.writelines('NETMASK=%s \n' % self.subnet)
            out_file.writelines('NETWORK=%s \n' % Configure_Files.pubNetwork)
            out_file.writelines('GATEWAY=%s \n' % self._dg)
            out_file.writelines(ifcfg_string)

if __name__ == "__main__": 
    server = New_VM(sys.argv[1:]) # Get everything after the script name
    #print str(server) + ' hostname is ' + str(server.hostname)
    #print str(server) + ' management IP is ' + str(server.managementIP)
    #print str(server) + ' public IP is ' + str(server.publicIP)
    #print str(server) + ' Default GW IP is ' + str(server.defaultGW)
    #print str(server) + ' Subnet IP is ' + str(server.subnet)
    #buildFile = Configure_Files(sys.argv[1:])
    #buildFile.network()
    #buildFile.eth0Config()

好的,再拍一次。

我请求用户在Configure_Files类中输入原始数据。但是,即使我没有从main调用Configure_Files类,我仍然会被提示输入原始数据。

当我使用-h选项运行脚本(python buildNetworkFile.py -h)时,我立即得到提示输入原始数据,一旦我输入原始数据(只有2个IP地址),我会显示帮助信息。

如果我从Configure_Class中取出原始输入代码,那么当使用'-h'选项运行脚本时,我不会再收到提示输入原始输入。

我认为我正在搞乱某处的异常处理,但无法弄清楚在哪里。但那只是我猜测......

1 个答案:

答案 0 :(得分:0)

根据你的解释,似乎你的代码只是在请求原始输入后“死”,因为只有在它尝试将该数据写入文件后,程序才意识到文件不存在,然后脚本失败。

尝试此操作以正确检查文件是否存在:

import os.path
os.path.exists(file_path)

如果文件或目录存在,语句os.path.exists(file_path)将返回True,否则返回False