windows 运行一个进程并退出而不等待它

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1718899/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 13:25:44  来源:igfitidea点击:

Run a process and quit without waiting for it

pythonwindows

提问by Tomas Sedovic

In Python under Windows: I want to run some code in a separate process. And I don't want the parent waiting for it to end. Tried this:

在 Windows 下的 Python 中:我想在单独的进程中运行一些代码。我不希望父母等待它结束。试过这个:

from multiprocessing import Process
from time import sleep

def count_sheeps(number):
    """Count all them sheeps."""
    for sheep in range(number):
        sleep(1)

if __name__ == "__main__":
    p = Process(target=count_sheeps, args=(5,))
    p.start()
    print("Let's just forget about it and quit here and now.")
    exit()

which starts the child process and continues executing. However, when the parent reaches the end, it still waits for the child to exit.

它启动子进程并继续执行。但是,当父级到达结束时,它仍然等待子级退出。

Is there a way of letting the parent quit even when the child is running? Sure, I could just run a new python interpreter using subprocess.Popenand feed to it the sheep-counting as a separate script.

有没有办法让父母在孩子跑步时退出?当然,我可以运行一个新的 python 解释器subprocess.Popen,并将绵羊计数作为单独的脚本提供给它。

Still, there's this whole module for playing with processes of Python code, so I'd like to take advantage of that instead of hacking on the OS. Also, it would be awesome if the same code worked everywhere where Python does, not just on Windows.

尽管如此,还有整个模块用于处理 Python 代码的进程,所以我想利用它而不是在操作系统上进行黑客攻击。此外,如果相同的代码在 Python 的任何地方都能工作,而不仅仅是在 Windows 上,那就太棒了。

回答by Daniel Paull

Use the subprocessmodule as other subprocess control methods (os.system, os.spawn*, os.popen*, popen2., commands.) are being deprecated:

使用该subprocess模块作为其他子进程控制方法(os.system、os.spawn*、os.popen*、popen2. 、commands.)正在被弃用:

from subprocess import Popen
Popen( [ "foo.exe", "arg1", "arg2", "arg3" )

See the Python doco, especially P_NOWAITexample.

请参阅 Python doco,尤其是P_NOWAIT示例。

You will have to start a new Python interpreter in the subprocess, so "foo.exe" above will likely be "python.exe".

您必须在子进程中启动一个新的 Python 解释器,因此上面的“foo.exe”可能是“python.exe”。

EDIT:

编辑:

Having just reviewed the multiprocessing module documentation:

刚刚查看了多处理模块文档:

join_thread(): Join the background thread. This can only be used after close() has been called. It blocks until the background thread exits, ensuring that all data in the buffer has been flushed to the pipe.

By default if a process is not the creator of the queue then on exit it will attempt to join the queue's background thread. The process can call cancel_join_thread()to make join_thread()do nothing.

cancel_join_thread(): Prevent join_thread()from blocking. In particular, this prevents the background thread from being joined automatically when the process exits – see join_thread().

join_thread(): 加入后台线程。这只能在调用 close() 后使用。它会阻塞直到后台线程退出,确保缓冲区中的所有数据都已刷新到管道中。

默认情况下,如果进程不是队列的创建者,那么在退出时它将尝试加入队列的后台线程。进程可以调用cancel_join_thread()make join_thread()do nothing。

cancel_join_thread(): 防止 join_thread()阻塞。特别是,这会阻止后台线程在进程退出时自动加入 - 请参阅join_thread()

It looks like you should be able to call cancel_join_thread()to get the behaviour you desire. I've never used this method (and was unaware of it's existence until a minute ago!), so be sure to let us know if it works for you.

看起来您应该能够调用cancel_join_thread()以获得您想要的行为。我从未使用过这种方法(直到一分钟前才意识到它的存在!),所以一定要让我们知道它是否适合你。

回答by ketorin

You can declare the process as daemon with p.daemon = True. As http://docs.python.org/2/library/threading.html#thread-objectssays: "The significance of this flag is that the entire Python program exits when only daemon threads are left."

您可以将进程声明为守护进程p.daemon = True。正如http://docs.python.org/2/library/threading.html#thread-objects所说:“这个标志的意义在于,当只剩下守护线程时,整个 Python 程序就会退出。”

from multiprocessing import Process
from time import sleep

def count_sheeps(number):
    """Count all them sheeps."""
    for sheep in range(number):
        sleep(1)

if __name__ == "__main__":
    p = Process(target=count_sheeps, args=(5,))
    p.daemon = True
    p.start()
    print("Let's just forget about it and quit here and now.")
    exit()

回答by Jochen Ritzel

Under Linux you could forkbut this won't work on Windows. I think the easiest way is to run a new Python process, by putting your count_sheepsin a seperate file and Popen('python count_sheeps.py')

在 Linux 下你可以,fork但这在 Windows 上不起作用。我认为最简单的方法是运行一个新的 Python 进程,将你count_sheeps的文件放在一个单独的文件中Popen('python count_sheeps.py')

回答by richo

You can always start a new thread, and call myNewThread.daemon(True) before invoking it's start() method.

您始终可以启动一个新线程,并在调用它的 start() 方法之前调用 myNewThread.daemon(True)。

That thread will continue to run when the main process exits.

当主进程退出时,该线程将继续运行。