【问题标题】:How to start threads in python that will continue when the parent process is exited?python - 如何在退出父进程时继续在python中启动线程?
【发布时间】:2017-09-22 11:30:08
【问题描述】:

我正在尝试为 python 中的 slurm 作业编写调度程序脚本。

基本上,我有一个包含在函数中的脚本,我们称之为job_array_scheduler(),它包含一个time.sleep() 循环。这预计将运行一天或更长时间。我希望能够从 python 内部将这个函数作为一个单独的线程启动,这样我就可以退出会话并且这个东西将继续运行。

我试过这样做:

import threading
scheduler_thread = threading.Thread(target=job_array_scheduler, args=args, daemon=True)
scheduler_thread.start()

但这会在我退出 python 会话时退出(即仅使用exit)。

如何解决这个问题,以保持上述线程处于活动状态,以便我可以退出 python 会话甚至注销我的用户?

我能想到的唯一方法是编写 another 脚本来环绕上述内容,因此我可以在 shell 后台运行它,执行类似python wrapper_script.py & 的操作,但我宁愿避免因为我必须为我想做的每一个这样的工作编写一个单独的外部脚本。

【问题讨论】:

  • 使用带有 multiprocessing 的进程而不是线程(在 python 中,由于 GIL,它无论如何都不能按预期工作)

标签: python multithreading subprocess daemon scheduler


【解决方案1】:

不要退出进程(线程是进程的一部分,不能超过它)。你想要的是daemonize (or detach)进程。

【讨论】:

    猜你喜欢
    • 2014-03-17
    • 1970-01-01
    • 1970-01-01
    • 2015-03-17
    • 1970-01-01
    • 2021-10-31
    • 1970-01-01
    • 2020-02-03
    • 1970-01-01
    相关资源
    最近更新 更多