1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Python ループ処理させたい関数が複数あるときのテクニック

Last updated at Posted at 2022-03-20

以下のように第一引数にループさせたい関数を、第二引数に前処理したい関数を指定するwrapper関数を作成して、マルチスレッドでtargetを指定する前にwrapして使ったりしています。

無限ループさせる例

import time

def wrap_loop_func(main_func: any, preprocessing_func: any = None):
    """関数をループさせる関数を返す"""
    def loop_func():
        if preprocessing_func:
            preprocessing_func()
        while True:
            main_func()
    return loop_func

def task():
    print('task')
    time.sleep(1)

def preprocessing():
    print('pre-processing has done.')
    

# loop_task = wrap_loop_func(task)
loop_task = wrap_loop_func(task, preprocessing)
loop_task()
実行結果
pre-processing has done.
task
task
task
.
..
...

終了条件と後処理をさせる例

上の処理だと味気ないので、終了条件と後処理も追加

import time

begin = time.time()

def wrap_loop_thread_task(main_func: any, exit_condition_func: any, preprocessing_func: any = None, postprocessing_func: any = None):
    """関数をループさせる関数を返す"""
    def loop_func():
        if preprocessing_func:
            preprocessing_func()
        while exit_condition_func():
            main_func()
        if postprocessing_func:
            postprocessing_func()
    return loop_func

def preprocessing():
    print('pre-processing has done.')

def postporcessing():
    print('post-processing has done.')

def exit_condition():
    """経過時間が3秒未満ならTrue"""
    return True if time.time() - begin < 3 else False

def task():
    print('task')
    time.sleep(1)

# loop_func = wrap_loop_thread_task(task,exit_condition)
loop_func = wrap_loop_thread_task(task,exit_condition,preprocessing,postporcessing)
loop_func()
実行結果
pre-processing has done.
task
task
task
post-processing has done.

終了条件が必要とは限らないので

第2引数がNoneの場合、lambda : Trueとする。(常にTrueを返す関数)

def wrap_loop_thread_task(main_func: any, exit_condition_func: any = None, preprocessing_func: any = None, postprocessing_func: any = None):
    """関数をループさせる関数を返す"""
    def loop_func():
        if preprocessing_func:
            preprocessing_func()
        if exit_condition_func:
            should_continue = exit_condition_func
        else:
            should_continue = lambda : True
        while should_continue():
            main_func()
        if postprocessing_func:
            postprocessing_func()
    return loop_func
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?