【问题标题】:Keep a class running in a python subprocess or thread or process保持一个类在 python 子进程或线程或进程中运行
【发布时间】:2022-01-20 10:40:31
【问题描述】:

我正在使用 Squish 自动化基于 Qt 的 GUI 应用程序。我在应用程序中递归查找 qt 对象。由于它很耗时,我想缓存一旦找到的对象以供以后重用。我有下面的类来维护字典中的对象缓存-

    
    def __init__(self):
        self.object_store = {}
    
    @staticmethod
    def instance():
        if '_instance' not in ObjectCache.__dict__:
            ObjectCache._instance = ObjectCache()
        return ObjectCache._instance
    
    def set(self, object_name, obj):
        self.object_store[object_name] = obj
    
    def remove(self, object_name):
        del self.object_store[object_name]
    
    def exists(self, object_name):
        if object_name in self.object_store:
            return True
        return False
    
    def get(self, object_name):
        return self.object_store[object_name]
        
    def get_all(self):
        return self.object_store

我的自动化脚本中有以下功能的装饰器,用于从该字典中添加/访问/删除 -

def object_caching_decorator(func):
    def wrapper(*args, **kwargs):
        object_cache = ObjectCache.instance()
        if object_cache.exists(func.__name__):
            try:
                if waitForObject(object_cache.get(func.__name__)):
                    return object_cache.get(func.__name__)
            except LookupError:
                object_cache.remove(func.__name__)
        obj = func(*args, **kwargs)
        object_cache.set(func.__name__, obj)
        return obj
    return wrapper

有人可能会问,为什么不能所有脚本都共享这个类对象?因为 Squish 工具会在启动每个测试脚本之前重置全局符号表,因此我需要一种方法来持久化这个对象。

如何让这个类保持运行,以便在另一个进程(Squish runner)上运行的脚本可以无缝访问它?

【问题讨论】:

  • 这能回答你的问题吗? How can I share a class between processes?
  • 如果你使用线程,全局实例是自动共享的,所以这对初学者来说可能更容易
  • @576i 感谢您的快速回复。我刚刚编辑了我的问题以提供完整的上下文。希望这有助于理解问题陈述。

标签: python-3.x subprocess python-multiprocessing python-multithreading squish


【解决方案1】:

每个 Squish 测试用例都在 squishr​​unner 的新实例(进程)和托管在其中的脚本解释器中执行。

Squish 在测试脚本中为您提供的对象引用实际上是代理对象,它们透明地(在幕后)为您访问应用程序进程内的实际对象,而您无需为这种“魔术”的发生做任何事情(或者大多数时候意识到它)。在测试用例中缓存/持久化这些对象是行不通的,也是不可能的。

此外,缓存对象引用是一个臭名昭著的问题,因为如果 AUT(被测应用程序)发生更改或以不同的方式使用,这些代理对象引用的对象的生命周期可能会改变。

除此之外,您应该重新审视查找对象的方式。很有可能有一种更好的方法来允许足够快的临时对象查找(如预期的那样)。 (如果有疑问,我建议联系 Squish 的供应商,因为您的维护合同或订阅他们的产品可以让您获得技术支持。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-02
    • 2011-10-11
    • 2015-01-04
    • 1970-01-01
    • 1970-01-01
    • 2012-04-05
    • 1970-01-01
    • 2014-09-23
    相关资源
    最近更新 更多