传递自定义参数python

时间:2015-06-23 11:23:42

标签: python timer

这是我的类充满静态函数的定义。我想在“sendLog”函数中使用它们,这个函数用时间间隔(这里是10秒)调用自己。当我运行这个解释器告诉我“TypeError:sendLog()至少需要5个参数(0给定)” 但是,如果我输入相同的参数,我将需要一次又一次地定义sendLog,因为它重复地称自己。我知道它不是那样但是无法解决它。

class AccessLog:

@staticmethod
def backupAccessLog(target, source):
    newfile = os.path.splitext(source)[0] + "_" + time.strftime("%Y%m%d-%H%M%S") + os.path.splitext(source)[1]
    copyfile(source,newfile)
    shutil.move(newfile,target)

@staticmethod
def emptyAccessLog(filename):
    open(filename, 'w').close()

@staticmethod
def postLogstoElastic():
    fileLogs = open("example.log", "rw+")
    fileBackups = open("logs_of_accesslog.log","rw+")
    lines = fileLogs.read().splitlines()
    logging.basicConfig(format='%(asctime)s>>>%(message)s',filename='logs_exceptions.log',level=logging.DEBUG)
    es = Elasticsearch(['http://localhost:9200/'], verify_certs=True)
    #es.create(index="index_log23June", doc_type="type_log23June")
    es.indices.create(index='index_log23June', ignore=400)
    i=0
    for item in lines:
        try:
            i+=1
            if bool(item):
                es.index(index="index_log23June",doc_type="type_log23June", body={"Log":item})
            else:
                print "a speace line ignored. at line number:", i
                raise ValueError('Error occurred on this line: ', i)
            print "lines[",i,"]:",item,"\n"

        except ValueError as err:
            logging.error(err.args)

@staticmethod
def sendLog(interval, worker_functions, iterations=1):
    def call_worker_functions():
        for f in worker_functions:
            f() #ERROR: Msg: 'NoneType' object is not callable
    for i in range(iterations):
        threading.Timer(interval * i, call_worker_functions).start()

我想用这一行调用这个方法:

try:
    AccessLog.AccessLog.sendLog(
    interval=10,
    worker_functions=(
        AccessLog.AccessLog.backupAccessLog("logbackups","example.log"),
        AccessLog.AccessLog.emptyAccessLog("example.log"),
        AccessLog.AccessLog.postLogstoElastic()
    ),
    iterations=999
)
except ValueError as err:
    logging.error(err.args)

“TypeError:sendLog()至少需要5个参数(给定0)”它看起来很正常但我该如何处理呢?

2 个答案:

答案 0 :(得分:2)

您是否尝试将@staticmethod设置为与函数相同的级别?

答案 1 :(得分:1)

显然,您希望{10}每隔10秒左右调用一次工作函数。 这是一个简单的方法:

sendLog()

现在就这样使用它:

class AccessLog:
    @staticmethod
    def sendLog(interval, worker_functions, iterations=1):
        def call_worker_functions():
            for f in worker_functions:
                f(*worker_functions[f])
        for i in range(iterations):
            threading.Timer(interval * i, call_worker_functions).start()

这只是众多方法中的一种,但没有必要像你那样将函数作为自己的参数传递。