且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

实现非阻塞等待的***方法?

更新时间:2021-08-03 01:31:43

鉴于相当奇怪的要求(一个不使用太多 CPU 的过程),这是相当紧凑的:

Given the rather bizarre requirements (a process that goes forever without using much CPU), this is reasonably compact:

import threading
dummy_event = threading.Event()
dummy_event.wait() 

...但是,我担心我会屈服于解决您的 Y 而不是您的 X 的诱惑.

...however, I fear I am succumbing to the temptation to solve your Y and not your X.

除此之外,如果您的平台不提供 threading 模块,这将不起作用.如果您尝试替换 dummy_threading 模块,dummy_event.wait() 会立即返回.

Besides which, this won't work if your platform doesn't provide the threading module. If you try to substitute the dummy_threading module, dummy_event.wait() returns immediately.

更新:如果您只是为了子进程而保持父进程运行,则可以使用 wait()Popen 对象,或 join() 方法 Process 对象.这两种方法都会无限期地阻塞,直到子进程结束.如果您正在使用其他一些子流程 API,那么肯定会有等效的功能可用.如果没有,获取进程的 PID 并使用 os.waitpid().

Update: if you are just keeping a parent process going for the sake of its subprocesses, you can use the wait()method on Popen objects, or the join() method on Process objects. Both of these methods will block indefinitely until the subprocess ends. If you're using some other subprocess API, there's bound to be equivalent functionality available. If not, get the PID of the process and use os.waitpid().