跳转到主要内容

用于在Python中使用multiprocessing库处理进程的对象和模式

项目描述

https://img.shields.io/travis/borgstrom/offspring.svg https://img.shields.io/codecov/c/github/borgstrom/offspring.svg Latest PyPI version

这是一个使用multiprocessing库在Python中处理进程的对象和模式的集合。

主要思想是,你将你的工作单元表达为一个对象上的简单方法,然后当该对象被实例化时,工作将在子进程中运行。

用例

Offspring是为了解决以下用例而构建的,用于在子进程中运行代码。

运行一次

from offspring import Subprocess


class MyTask(Subprocess):
    def init(self, arg1):
        # This is run in the parent process and is used to prepare your object.
        # It receives whatever arguments were supplied to the constructor.
        self.arg1 = arg1

    def run(self):
        # This will be run in the child process and completes your work.
        # ...


MyTask('this is arg1').wait()

循环运行

from offspring import SubprocessLoop


class MyTask(SubprocessLoop):
    def init(self, arg1):
        # This is the same as init for Subprocess.
        self.arg1 = arg1

    def begin(self):
        # Called before the start of the loop in your child process.
        # ...

    def loop(self):
        # Called each loop iteration in your your child process.
        # It can return a sleep duration until the next loop, or False to stop the loop.
        # ...

    def end(self):
        # Called after the end of the loop, before termination in your child process.
        # ...


MyTask('this is arg1').wait()

实现细节

.init(*args, **kwargs)

在创建你的类的一个实例时调用。它接收与__init__方法相同的参数,因此鼓励你明确定义你期望的参数。

.start()

创建子进程。除非你将EXPLICIT_START设置为True,否则这会自动调用。

.wait()

如果你需要等待你的子进程,可以在你的Subprocess对象上调用.wait。这只是在multiprocessing.Process对象上的.join的快捷方式。

.shutdown()

这将向子进程发送TERM信号,除非TERMINATE_ON_SHUTDOWNFalse,然后调用.wait来连接子进程。它会在父进程通过atexit模块退出时自动调用。

.process

每个Subprocess对象都有一个.process属性,它是multiprocessing.Process对象。

WAIT_FOR_CHILD

默认为False

如果将您的 Subprocess 类设置为 True,则将使用 Pipe 来阻塞父进程,直到子进程启动。这在你想要确保即使父进程快速退出,Subprocess 对象也被启动且调用了 .run 方法时非常有用。

class MyTask(Subprocess):
    WAIT_FOR_CHILD = True

    def run(self):
        print("This will always print")

MyTask()

SubprocessLoop 类这样做是为了确保你的对象调用了 beginend 方法(循环可能不会调用,因为在启动期间接收到的 TERM 信号将阻止循环实际完成,除了 beginend 外)。

TERMINATE_ON_SHUTDOWN

默认为 True

如果设置为 False,则在 Subprocess 对象上调用 .shutdown 时,子进程在连接之前不会被终止。这意味着父进程将阻塞,直到子进程完成 .run 函数。

import time

class MyTask(Subprocess):
    TERMINATE_ON_SHUTDOWN = False

    def run(self):
        time.sleep(2)

MyTask()

EXPLICIT_START

默认为False

如果设置为 True,则在实例化对象时,你必须显式调用 .start(),子进程才会被启动。

class MyTask(Subprocess):
    EXPLICIT_START = True

    def run(self):
        print("Running!")


task = MyTask()
# Do some other work
task.start()
# Running! is now printed

项目详情


下载文件

下载适用于您平台的文件。如果您不确定选择哪个,请了解更多关于 安装包 的信息。

源代码发行版

offspring-0.1.1.tar.gz (4.2 kB 查看哈希值)

上传时间 源代码

构建发行版

offspring-0.1.1-py2.py3-none-any.whl (6.7 kB 查看哈希值)

上传时间 Python 2 Python 3

支持者:

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误日志 StatusPage StatusPage 状态页面