在Class内执行函数而不是之前

时间:2015-06-22 16:49:30

标签: python

我创建了类CacheFile()来在文件中存储信息。

基本做的是检查文件是否较旧并更新内容。

问题是当我尝试在属性cmd_update中使用一个函数时。该函数在我想要之前执行。

def lsnports_cmd():

    lsnports_data = commands.getoutput('ssh -l xxxx command_foo_bar)

lsnports = cachefile.CacheFile('lsnports.cache', '600', lsnports_cmd())
lsnports.cache()

lsnports_cmd在cachefile.CacheFile(args ..)上执行,我需要在调用cacheUpdate()时只在lsnports.cache()内部执行。

我该怎么做?

Class CacheFile:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Imports
############################################################################################### 
import os 
import time

###############################################################################################

class CacheFile():
    """It's is a simple cache file ... 
       Attributes:

       filename        the file you want store;
       time_refresh    time of the refresh in seconds 
       cmd_update      the output you want store in the cache file
    """

    def __init__(self, filename, time_refresh, cmd_update):
        self.filename = filename
        self.time_refresh = int(time_refresh)
        self.cmd_update = cmd_update

    def cache(self):
        ''' Main of Class CacheFile.
            It's get the cache or update if cache don't exists or depracieted
        '''

        def cacheUpdate():
            ''' Update the file cache '''
            global text_file
            text_file = open(self.filename, 'w')
            text_file.write("%s" % self.cmd_update)
            text_file.close()

        def readCache():
            ''' Read the file cache content '''
            text_file = open(self.filename, 'r')
            print text_file.read()
            text_file.close()


        # verify if cache file exists
        if os.path.isfile(self.filename):

            if (time.time() - os.path.getmtime(self.filename)) > self.time_refresh:
                # if time to refresh is > then file it'll be updated
                cacheUpdate()
                readCache()

            else:
                # if time to refresh is < just use the file
                readCache()

        # if file don't exists the file is created
        else:
            cacheUpdate()

1 个答案:

答案 0 :(得分:1)

你让它落后了。创建CacheFile实例时不要调用该函数:

lsnports = cachefile.CacheFile('lsnports.cache', '600', lsnports_cmd)

执行在更新缓存时调用该函数:

text_file.write("%s" % self.cmd_update())