如何使用python 3.x在类方法中访问全局变量

问题描述 投票:0回答:1

我遇到一个问题,我有一个创建批处理文件并将其文件名存储在名为“ filename”的变量中的类方法。我有另一个方法来运行批处理文件,该批处理文件调用在另一个方法中创建的“文件名”。但是我得到的响应类对象没有属性“文件名”。如何在同一个类中的一个方法中创建此变量并在另一个方法中调用它?

我尝试设置self.filename = filename。我试过在类外设置全局文件名= None,然后在类init本身内设置文件名。我已包含以下代码段代码:

class SNMPPage(tk.Frame):
    def __init__(self, root=None):
        tk.Frame.__init__(self, root)
        self.root = root
        self.root.title('SNMP Get Set Test')
        global filename
        self.init_gui()

    def create_batch(self):
        i = 0
        #path = os.getcwd()
        global filename
        #ping_set = 'ping -n 1 ' + e1.get() + ' | find "TTL=" >null\nif errorlevel 1 (\n    echo host not reachable\n    pause\n)\n'
        snmp_get = 'snmpget' + " -Os" + " -mall " + "-c " + self.e3.get() + ' -v2c' + ' ' + self.e1.get() + ' ' + self.e2.get() + "\n"
        snmp_set = 'snmpset' + " -Os" + " -mall " + "-c " + self.e3.get() + ' -v2c' + ' ' + self.e1.get() + ' ' + self.e2.get() + \
                    ' i' + ' 1\n'
        timeout = 'timeout ' + self.e4.get() + '\n'
        filename = path + '\\SNMPBatchrun' + getdatetime('datetime') + ".bat"
        with open(filename, 'w+') as outfile:
            while i < 10:
                #outfile.write(ping_set)
                outfile.write(snmp_get)
                outfile.write(snmp_set)
                outfile.write(timeout)
                i += 1
        loggermodule.module_logger.debug('Batch File Created: {}'.format(filename))
        logger.debug('Batch file created: {}'.format(filename))


    def start_batch(self):
        try:
            global filename
            logger.debug('Starting batch file execution')
            loggermodule.module_logger.debug('Starting batch file execution')
            #s = subprocess.check_output([filename]).decode('utf-8')
            process = subprocess.Popen([filename], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            output, code = process.communicate()
            self.root.update()

            ''' Logger'''
            for line in code.decode('utf-8').splitlines():
                if 'Waiting for' not in line:
                    logger.debug(line)
                    loggermodule.module_logger.debug(line)
                for line in output.decode('utf-8').splitlines():
                    if 'Waiting for' not in line:
                        logger.debug(line)
                        loggermodule.module_logger.debug(line)
            loggermodule.module_logger.debug("Batch job completed")
            logger.debug("Batch job completed")
            # with open(log_file, 'w+') as outfile:
            #    for line in s.splitlines():
            #        outfile.write(line)
            return self.output
        except subprocess.CalledProcessError as e:
            logger.exception(e)
            loggermodule.module_logger.debug(e)
            loggermodule.module_logger.debug("There was an error, Batch file stopped. Check Log file")
'SNMPPage' object has no attribute 'filename'

我希望使用create_batchfile创建文件(成功完成),但是当我运行方法start_batchfile时,由于SNMPPage没有属性“文件名”,它失败了


python-3.x class oop variables global
1个回答
0
投票

根据您在评论中的澄清。

为了在方法之间共享变量,这应该是一个对象属性。我不知道为什么它对您不起作用,但是您应该使用此基本模式。

class SNMPPage(tk.Frame):
    def __init__(self, root=None):
    self.filenmae = None
    ....

def create_batch(self):
    self.filenmae = 'foo'

def start_batch(self):
    # use self.filenmae
    print(self.filenmae)
© www.soinside.com 2019 - 2024. All rights reserved.