简体   繁体   English

python -c cmd将等待所有进程完成

[英]python -c cmd will wait all process finish

Codes: 代码:

File: script.py 档案:script.py

from multiprocessing import Process


def func():
    async_process()
    print('OK')
    return 123

def func2(args):
    # do a lot of things here
    # ...
    pass

def async_process():
    p = Process(target=func2, args=args)
    p.daemon = False 
    p.start()

When I directly call the func() in Python script, I can get the returned value immediately, this is what I expect. 当我直接在Python脚本中调用func()时,我可以立即获得返回值,这就是我所期望的。

But, when I call the func() in command line like this: 但是,当我像这样在命令行中调用func()时:

python -c "from script import func;func()"

The command line will finish executing until the new created process finished itself. 命令行将完成执行,直到新创建的进程本身完成为止。 This is not I want. 这不是我想要的。

How should I change the program or how should I write the script to ensure: 如何更改程序或如何编写脚本以确保:

  1. I can call the func() in command line; 我可以在命令行中调用func();

  2. The command line will immediately return the value when the func() is finished, and won't wait for the new created process. 当func()完成时,命令行将立即返回该值,并且不会等待新创建的进程。

  3. The new created process can keeps running. 新创建的进程可以继续运行。

That's because the child process created in async_process() is not detached from its parent, hence the parent has to wait for the child to finish before exiting. 这是因为在async_process()中创建的子进程未与其父进程分离,因此父进程必须等待子进程完成后再退出。 If you want to create a daemon process in the Unix meaning of the term, you'll have to use the double-fork method to detach the child from its parent and hand over control to the OS' scheduler. 如果要在Unix的术语中创建守护进程,则必须使用double-fork方法将子代与其父代分离,并将控制权移交给OS的调度程序。 This looks to be a decent recipe for creating Unix daemon processes in python 似乎是在python中创建Unix守护进程的不错方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM