运行一个进程,不用等我就退出

2024-06-12 03:38:40 发布

您现在位置:Python中文网/ 问答频道 /正文

在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()

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

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

不过,这里有一个完整的模块用于处理Python代码的进程,所以我想利用这个模块而不是对操作系统进行黑客攻击。另外,如果同一代码在Python的任何地方都能工作,而不仅仅是在Windows上,那将是非常棒的。


Tags: 模块and代码fromimportnumber进程windows
3条回答

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

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

See the Python doco,尤其是P_NOWAIT示例。

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

编辑:

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

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().

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

您可以用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()

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

相关问题 更多 >