用于在Python中使用multiprocessing库处理进程的对象和模式
项目描述
这是一个使用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_SHUTDOWN是False,然后调用.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 类这样做是为了确保你的对象调用了 begin 和 end 方法(循环可能不会调用,因为在启动期间接收到的 TERM 信号将阻止循环实际完成,除了 begin 和 end 外)。
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 的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | e30c37b5f98c5bc2e0889a0c24a3ced91fac10f3bff090873d3c14ea7acc0c53 |
|
MD5 | 236db3833cc7f1008732c36319e8862a |
|
BLAKE2b-256 | 08511e7130113a14882969b78081ee11bc159946b70fbb098bd839903239f613 |
offspring-0.1.1-py2.py3-none-any.whl 的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | 3fe701aa67a982e899cfefaecdbec29c2223fd93779aaa60e9dd3e74d24ac6d0 |
|
MD5 | 2a30ed78a227031a1abadeed41454d5b |
|
BLAKE2b-256 | 61d3cd60771acf94c9171521288005784812692a729cd76a82ddcf714e0fcbe8 |