如何等到用户关闭Python的过程?

发布于 2025-01-28 10:21:40 字数 440 浏览 2 评论 0原文

我想创建一个程序,以启动新的流程,然后等到用户或其他程序杀死该过程。

但是我不明白为什么子过程创建的过程是在一小部分时间之后完成的,而不是通过用户关闭流程的。

import subprocess
import psutil

old_process = {p.pid for p in psutil.process_iter()}
calc_process = subprocess.Popen('C:\Windows\System32\calc')
new_process = {p.pid for p in psutil.process_iter()}
process = list(new_process - old_process)[0]

while psutil.pid_exists(process):
    print('Process running')
print('Done')

I want to create a program that init a new process and then wait until thhis process was killed by user or another program.

But i cant understand why the process create by subprocess is finished after a fraction of time and not by the user closing the process.

import subprocess
import psutil

old_process = {p.pid for p in psutil.process_iter()}
calc_process = subprocess.Popen('C:\Windows\System32\calc')
new_process = {p.pid for p in psutil.process_iter()}
process = list(new_process - old_process)[0]

while psutil.pid_exists(process):
    print('Process running')
print('Done')

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

_失温 2025-02-04 10:21:40

popen具有使用“ noreferrer”>“ noreferrer”> 轮询 方法。

from subprocess import Popen

process = Popen('C:\Windows\System32\calc')
process.wait()

while not process.poll():
    print('Process running')

print('Done')

Popen has this built in using the poll method.

from subprocess import Popen

process = Popen('C:\Windows\System32\calc')
process.wait()

while not process.poll():
    print('Process running')

print('Done')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文