代码之家  ›  专栏  ›  技术社区  ›  JacquesB

启动单独的进程

  •  14
  • JacquesB  · 技术社区  · 14 年前

    我想要一个脚本来启动一个新进程,这样新进程在初始脚本退出后继续运行。我希望我能 multiprocessing.Process 开始一个新的进程,并设置 daemon=True 以便在创建的进程继续运行时退出主脚本。

    但是,当主脚本退出时,第二个进程似乎会自动终止。这是预期的行为,还是我做错了什么?

    5 回复  |  直到 12 年前
        1
  •  14
  •   Justin Ardini    14 年前

    从Python文档:

    当进程退出时,它会尝试 终止其所有守护子进程

    这是预期的行为。

        2
  •  13
  •   unutbu    7 年前

    如果您使用的是unix系统,则可以使用 os.fork :

    import os
    import time
    
    pid=os.fork()
    if pid:
        # parent
        while True:
            print("I'm the parent")
            time.sleep(0.5)    
    else:
        # child
        while True:
            print("I'm just a child")
            time.sleep(0.5)
    

    运行此命令将创建两个进程。你可以杀死父母而不杀死孩子。 例如,当您运行脚本时,您将看到如下内容:

    % script.py
    I'm the parent
    I'm just a child
    I'm the parent
    I'm just a child
    ...
    

    使用ctrl-Z停止脚本:

    ^Z
    [1]+  Stopped                 script.py
    

    % ps axuw | grep script.py
    unutbu    6826  0.1  0.1  33792  6388 pts/24   T    15:09   0:00 python /home/unutbu/pybin/script.py
    unutbu    6827  0.0  0.1  33792  4352 pts/24   T    15:09   0:00 python /home/unutbu/pybin/script.py
    unutbu    6832  0.0  0.0  17472   952 pts/24   S+   15:09   0:00 grep --color=auto script.py
    

    终止父进程:

    % kill 6826
    

    将script.py还原到前台:

    % fg
    script.py
    Terminated
    

    % I'm just a child
    I'm just a child
    I'm just a child
    ...
    

    杀死孩子(在一个新的终端)

    % kill 6827
    
        3
  •  10
  •   Philipp    14 年前

    只需使用 subprocess 模块:

    import subprocess
    subprocess.Popen(["sleep", "60"])
    
        4
  •  1
  •   Community CDub    8 年前

    下面是一个相关的问题,其中一个答案给出了一个很好的解决方案:

    "spawning process from python"

        5
  •  0
  •   ilias iliadis    7 年前

    如果您在unix系统上( using docs ):

    #!/usr/bin/env python3
    import os
    import sys
    import time
    import subprocess
    import multiprocessing
    from multiprocessing import Process
    
    def to_use_in_separate_process(*args):
        print(args)
    
        #check args before using them:
        if len(args)>1:
            subprocess.call((args[0], args[1]))
            print('subprocess called')
    
    def main(apathtofile):
        print('checking os')
        if os.name == 'posix':
            print('os is posix')
            multiprocessing.get_context('fork')
            p = Process(target=to_use_in_separate_process, args=('xdg-open', apathtofile))
            p.run()
        print('exiting def main')
    
    if __name__ == '__main__':
        #parameter [1] must be some file that can be opened by xdg-open that this
        #program uses.
        if len(sys.argv)>1:
            main(sys.argv[1])
            print('we can exit now.')
        else:
            print('no parameters...')
        print('mother program will end now!')
        sys.exit(0)