Python:在创建子进程后终止父进程

时间:2017-08-02 08:51:26

标签: python-3.x multiprocessing

我有一个用Python编写的轮询作业,每15分钟执行一次,以检查作业表中条目的状态是否为True。如果状态为true,那么我需要从表中获取值并将它们作为参数传递给另一个执行某些操作的脚本。

我在Python的Process模块中使用Multiprocessing创建子进程,但是在启动这些进程后我无法退出轮询作业(父脚本)。即使在创建子项后写入sys.exit(),轮询工作也会一直等待孩子完成。

#pollingjob.py
import sys
import multiprocessing
from multiprocessing import Process
from secondscript import secondscriptfunction

def createParallelBatches(a,b,c):
    for i in [1,2,3]:
        p1 = Process(target=secondscriptfunction,args=(a,b,c)).start()
    sys.exit()

if __name__=='__main__':
    # Check the table for *status=True* rows
    # If such rows exit call CreateParallelBatches with the column values

我无法理解的是,为什么sys.exit()不会让我退出程序而将生成的进程留作孤儿。我尝试了subprocess模块,但它的行为方式也相同。我不希望父进程等待其子进程完成。任何帮助,将不胜感激。感谢。

2 个答案:

答案 0 :(得分:0)

您需要在外部启动独立的子流程。这是一种方法:

  1. 将secondscript函数放入一个可执行的python文件
  2. 档案runscript.py

    import sys
    from secondscript import secondscriptfunction
    if __name__=='__main__':
            secondscriptfunction(sys.argv[1:]) #passing arguments to the func
    
    1. 在脚本中使用subprocess.popen:
    2. 档案pollingjob.py

      import subprocess
      import shlex
      def createParallelBatches(a,b,c):
          for i in [1,2,3]:
             command = "python runscript.py %s %s %s "%(a,b,c)
             cmd_args = shlex.split(command)
             subprocess.Popen(cmd_args)
          sys.exit()
      

答案 1 :(得分:0)

只需从当前流程对象的_children集合中删除流程对象,父流程将立即退出。

该多处理模块管理私有集中的子进程,并在当前进程退出时将其加入。如果您不关心儿童,则可以将其从集合中删除。

            process = multiprocessing.Process(target=proc_main)
            multiprocessing.current_process()._children.discard(process)
            exit(0)
相关问题