使用多处理库在python中处理进程的对象和模式
offspring的Python项目详细描述
这是使用多处理库在python中处理进程的对象和模式的集合。
主要思想是将工作单元表示为对象上的简单方法,然后当该对象是 实例化的工作将在子进程中运行。
用例
构建子代是为了解决以下在子流程中运行代码的用例。
运行一次
fromoffspringimportSubprocessclassMyTask(Subprocess):definit(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=arg1defrun(self):# This will be run in the child process and completes your work.# ...MyTask('this is arg1').wait()
循环运行
fromoffspringimportSubprocessLoopclassMyTask(SubprocessLoop):definit(self,arg1):# This is the same as init for Subprocess.self.arg1=arg1defbegin(self):# Called before the start of the loop in your child process.# ...defloop(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.# ...defend(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()加入子进程。每当父进程通过^ {TT16}$退出时,就会自动调用它。 模块。
.process
每个Subprocess对象都有一个.process属性,即multiprocessing.Process对象。
WAIT_FOR_CHILD
默认为False。
如果在Subprocess类上设置为True,则Pipe将用于阻止父进程,直到子进程 已经开始了。当您希望确保启动Subprocess对象并调用.run时,这非常有用。 即使父进程很快退出。
classMyTask(Subprocess):WAIT_FOR_CHILD=Truedefrun(self):print("This will always print")MyTask()
SubprocessLoop类这样做是为了确保您的对象调用了begin&;end(loop可能不是 作为在启动期间接收到的术语信号调用将阻止循环实际完成 begin&;end)。
TERMINATE_ON_SHUTDOWN
默认为True。
如果设置为False,则当对Subprocess对象调用.shutdown时,子进程将不会 在加入之前终止。这意味着父函数将阻塞,直到子函数完成.run为止。
importtimeclassMyTask(Subprocess):TERMINATE_ON_SHUTDOWN=Falsedefrun(self):time.sleep(2)MyTask()
EXPLICIT_START
默认为False。
如果设置为True,则在实例化对象时,必须在子进程之前显式调用.start()。 将产生。
classMyTask(Subprocess):EXPLICIT_START=Truedefrun(self):print("Running!")task=MyTask()# Do some other worktask.start()# Running! is now printed