抱歉,如果标题很奇怪。让我解释一下。
假设有 handler.py
:
import funcs
import requests
def initialize_calculate(data):
check_data(data)
funcs.calculate(data) # takes a lot of time like 30 minutes
print('Calculation launched')
requests.get('hostname', params={'func':'calculate', 'status':'launched'})
这里是funcs.py
:
import requests
def calculate(data):
result = make_calculations(data)
requests.get('hostname',params={'func':'calculate', 'status':'finished', 'result':result})
所以我想要的是处理程序可以初始化另一个函数,无论在哪里,但不会等到它结束,因为我想通知客户端进程已启动,并且当它完成时,该进程本身将发送结果当它完成时。
如何使用 initialize_calculate
中的函数计算启动独立进程?
我想知道是否可以在没有非 native 库或框架的情况下实现。
最佳答案
如果您不想使用第三方库,例如 daemonocle践行“乖”Unix-Daemon , 你可以
使用subprocess.Popen()
创建一个独立的流程。另一种选择是修改 multiprocessing.Process
以防止在父级退出时子级自动加入。
subprocess.Popen()
与 subprocess.Popen()
您可以通过指定命令和参数(例如从终端手动指定)来启动新进程。这意味着您需要使 funcs.py 或另一个文件成为顶级脚本,用于解析来自 stdin 的字符串参数,然后使用这些参数调用 funcs.calculate() 。
我将您的示例归结为本质,因此我们不必阅读太多代码。
funcs.py
#!/usr/bin/env python3
# UNIX: enable executable from terminal with: chmod +x filename
import os
import sys
import time
import psutil # 3rd party for demo
def print_msg(msg):
print(f"[{time.ctime()}, pid: {os.getpid()}] --- {msg}")
def calculate(data, *args):
print_msg(f"parent pid: {psutil.Process().parent().pid}, start calculate()")
for _ in range(int(500e6)):
pass
print_msg(f"parent pid: {psutil.Process().parent().pid}, end calculate()")
if __name__ == '__main__':
if len(sys.argv) > 1:
calculate(*sys.argv[1:])
subp_main.py
#!/usr/bin/env python3
# UNIX: enable executable from terminal with: chmod +x filename
if __name__ == '__main__':
import time
import logging
import subprocess
import multiprocessing as mp
import funcs
mp.log_to_stderr(logging.DEBUG)
filename = funcs.__file__
data = ("data", 42)
# in case filename is an executable you don't need "python" before `filename`:
subprocess.Popen(args=["python", filename, *[str(arg) for arg in data]])
time.sleep(1) # keep parent alive a bit longer for demo
funcs.print_msg(f"exiting")
对于测试很重要,从终端运行,例如不是 PyCharm-Run,因为它不会显示子进程打印的内容。在下面的最后一行中,您会看到子进程的parent-id 更改为 1
,因为子进程在父进程退出后被 systemd (Ubuntu) 采用。
$> ./subp_main.py
[Fri Oct 23 20:14:44 2020, pid: 28650] --- parent pid: 28649, start calculate()
[Fri Oct 23 20:14:45 2020, pid: 28649] --- exiting
[INFO/MainProcess] process shutting down
[DEBUG/MainProcess] running all "atexit" finalizers with priority >= 0
[DEBUG/MainProcess] running the remaining "atexit" finalizers
$> [Fri Oct 23 20:14:54 2020, pid: 28650] --- parent pid: 1, end calculate()
类 OrphanProcess(multiprocessing.Process)
如果您寻找更方便的东西,那么您不能按原样使用高级multiprocessing.Process
,因为它不会让父进程在之前退出 child ,正如你所要求的。当父进程关闭时,常规子进程要么加入(等待),要么终止(如果您为 Process
设置了 daemon
标志)。这种情况在 Python 中仍然会发生。请注意,daemon
-标志不会使进程成为 Unix-Daemon。命名的常见来源是 confusion .
我将 multiprocessing.Process
子类化以关闭自动加入,并花一些时间研究源代码并观察是否 zombies可能会成为一个问题。因为修改关闭了父进程中的自动加入,所以我建议使用“forkserver”作为 Unix 上新进程的启动方法(如果父进程已经是多线程的,这总是一个好主意),以防止僵尸子进程停留太久父级仍在运行。当父进程终止时,它的子僵尸进程最终会得到 reaped通过 systemd/init.运行 multiprocessing.log_to_stderr()
显示一切都干净地关闭,因此到目前为止似乎没有任何问题。
考虑这种方法是实验性的,但它可能比使用原始的 os.fork() 重新发明部分广泛的多处理机制安全得多,只是为了添加这一项功能。对于子级中的错误处理,请编写一个 try- except block 并记录到文件。
orphan.py
import multiprocessing.util
import multiprocessing.process as mpp
import multiprocessing as mp
__all__ = ['OrphanProcess']
class OrphanProcess(mp.Process):
"""Process which won't be joined by parent on parent shutdown."""
def start(self):
super().start()
mpp._children.discard(self)
def __del__(self):
# Finalizer won't `.join()` the child because we discarded it,
# so here last chance to reap a possible zombie from within Python.
# Otherwise systemd/init will reap eventually.
self.join(0)
orph_main.py
#!/usr/bin/env python3
# UNIX: enable executable from terminal with: chmod +x filename
if __name__ == '__main__':
import time
import logging
import multiprocessing as mp
from orphan import OrphanProcess
from funcs import print_msg, calculate
mp.set_start_method("forkserver")
mp.log_to_stderr(logging.DEBUG)
p = OrphanProcess(target=calculate, args=("data", 42))
p.start()
time.sleep(1)
print_msg(f"exiting")
再次从终端测试以将子打印输出到标准输出。在第二个提示符上打印所有内容后,如果 shell 似乎挂起,请按 Enter 键以获取新提示符。这里的parent-id保持不变,因为从操作系统的角度来看,父进程是forkserver进程,而不是orph_main.py的初始主进程。
$> ./orph_main.py
[INFO/MainProcess] created temp directory /tmp/pymp-bd75vnol
[INFO/OrphanProcess-1] child process calling self.run()
[Fri Oct 23 21:18:29 2020, pid: 30998] --- parent pid: 30997, start calculate()
[Fri Oct 23 21:18:30 2020, pid: 30995] --- exiting
[INFO/MainProcess] process shutting down
[DEBUG/MainProcess] running all "atexit" finalizers with priority >= 0
[DEBUG/MainProcess] running the remaining "atexit" finalizers
$> [Fri Oct 23 21:18:38 2020, pid: 30998] --- parent pid: 30997, end calculate()
[INFO/OrphanProcess-1] process shutting down
[DEBUG/OrphanProcess-1] running all "atexit" finalizers with priority >= 0
[DEBUG/OrphanProcess-1] running the remaining "atexit" finalizers
[INFO/OrphanProcess-1] process exiting with exitcode 0
关于python - 如何在函数内初始化并行独立进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64396700/