1

我正在为 OpenERP 创建一个模块,我必须在其中启动一个正在进行的过程。

OpenERP 在一个连续的循环中运行。当我单击一个按钮时,我的进程必须启动,并且它必须继续运行,而不会阻止 OpenERP 的执行。

为了简化它,我有这个代码:

#!/usr/bin/python
import multiprocessing
import time

def f(name):
    while True:
        try:
            print 'hello', name
            time.sleep(1)
        except KeyboardInterrupt:
            return

if __name__ == "__main__":
    count = 0
    while True:
        count += 1
        print "Pass %d" % count
        pool = multiprocessing.Pool(1)
        result = pool.apply_async(f, args=['bob'])
        try:
            result.get()
        except KeyboardInterrupt:
            #pass
            print 'Interrupted'
        time.sleep(1)

执行时,Pass 1打印一次,然后打印无穷无尽的系列hello bob直到CTRL+C被按下。然后Pass 2得到等等,如下图:

Pass 1
hello bob
hello bob
hello bob
^CInterrupted
Pass 2
hello bob
hello bob
hello bob
hello bob

我希望通行证与hello bob's 保持平行增加。

我怎么做?

4

1 回答 1

2

在这里你可以做什么,你可以在服务器内存下创建 Python 的多线程实现,它将独立运行,然后是服务器执行线程。将使用这背后的技巧是我们将在您需要的单击时从服务器分叉一个线程,我们会将所有服务器变量单独副本分配给新线程,以便线程将独立执行,然后在进程结束时您必须提交事务为此进程将不是主服务器进程。这里是一个小例子,你可以如何做到这一点。

import pprint
import pooler
from threading import Thread
import datetime
import logging
pp = pprint.PrettyPrinter(indent=4)

class myThread(Thread):
    """
    """
    def __init__(self, obj, cr, uid, context=None):
        Thread.__init__(self)
        self.external_id_field = 'id'
        self.obj = obj
        self.cr = cr
        self.uid = uid
        self.context = context or {}
        self.logger = logging.getLogger(module_name)
        self.initialize()

    """
        Abstract Method to be implemented in the real instance
    """
    def initialize(self):
        """
            init before import
            usually for the login
        """
        pass

    def init_run(self):
        """
            call after intialize run in the thread, not in the main process
            TO use for long initialization operation
        """
        pass

    def run(self):
        """
            this is the Entry point to launch the process(Thread)
        """
        try:
            self.init_run()
            #Your Code Goes Here
            #TODO Add Business Logic
            self.cr.commit()
        except Exception, err:
            sh = StringIO.StringIO()
            traceback.print_exc(file=sh)
            error = sh.getvalue()
            print error
        self.cr.close()

像这样,您可以在某些模块中添加一些代码,例如(6.1 或中继中的 import_base 模块)现在接下来您可以做的是扩展实现,然后创建服务实例,或者您可以直接开始分叉,如下所示代码:

    service = myServcie(self, cr, uid, context)
    service.start()

现在我们启动运行速度更快的后台服务,让您可以自由使用 UI。

希望这对你有帮助 谢谢

于 2012-06-06T10:17:17.427 回答