python如何避免同一函数的多个运行实例

2024-09-27 00:15:29 发布

您现在位置:Python中文网/ 问答频道 /正文

在python脚本中,我有一个core dumped,我想这是因为同一个函数同时被调用两次。在

该功能是读取gtk窗口中的Vte终端

def term(self, dPluzz, donnees=None):
    text = str(self.v.get_text(lambda *a: True).rstrip())
    [...]
    print "Here is the time " + str(time.time())

def terminal(self):    
    self.v = vte.Terminal()
    self.v.set_emulation('xterm')
    self.v.connect ("child-exited", lambda term: self.verif(self, dPluzz))
    self.v.connect("contents-changed", self.term)

结果:

^{pr2}$

如何避免函数的重复执行?在


Tags: lambda函数textcoreself功能脚本gtk
2条回答

我创建了一个python decorator(mutli平台兼容),它提供了一种避免并发执行的机制。 用法是:

@lock('file.lock')
def run():
    # Function action
    pass

个人而言,我习惯使用相对路径:

^{pr2}$

装饰师:

import os

def lock(lock_file):
    """
    Usage:
        @lock('file.lock')
        def run():
            # Function action
    """
    def decorator(target):

        def wrapper(*args, **kwargs):

            if os.path.exists(lock_file):
                raise Exception('Unable to get exclusive lock.')
            else:
                with open(lock_file, "w") as f:
                    f.write("LOCK")

            # Execute the target
            result = target(*args, **kwargs)

            remove_attempts = 10
            os.remove(lock_file)
            while os.path.exists(lock_file) and remove_attempts >= 1:

                os.remove(lock_file)
                remove_attempts-=1

            return result
        return wrapper
    return decorator

对于多线程调用

有一个用于管理多线程调用的unix解决方案:https://gist.github.com/mvliet/5715690

别忘了感谢这篇文章的作者(不是我)。在

双重执行必须是contents-changed事件触发两次的结果。在

您只需检查term函数之前是否已经执行过它,如果已经执行过,则退出。在

term函数的开头添加以下两行:

    if hasattr(self, 'term_has_executed'): return
    self.term_has_executed = True

相关问题 更多 >

    热门问题