如何在 Linux 上的 Python 中检查进程是否处于活动状态?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1114312/
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-11-03 21:30:58  来源:igfitidea点击:

How do I check if a process is alive in Python on Linux?

pythonprocess

提问by Uri

I have a process id in Python. I know I can kill it with os.kill(), but how do I check if it is alive ? Is there a built-in function or do I have to go to the shell?

我在 Python 中有一个进程 ID。我知道我可以用 os.kill() 杀死它,但是我如何检查它是否还活着?是否有内置函数或者我必须去shell?

回答by Mikhail Churbanov

Use subprocessmodule to spawn process. There is proc.poll()function - it returns Noneif process is still alive, otherwise it returns process returncode.

使用subprocess模块生成进程。有proc.poll()函数 -None如果进程仍然存在,它返回,否则返回进程返回码。

http://docs.python.org/library/subprocess.html

http://docs.python.org/library/subprocess.html

回答by Dustin

os.killdoes not kill processes, it sends them signals (it's poorly named).

os.kill不杀死进程,它向它们发送信号(它的名字很糟糕)。

If you send signal 0, you can determine whether you are allowed to send other signals. An error code will indicate whether it's a permission problem or a missing process.

如果发送信号0,则可以确定是否允许发送其他信号。错误代码将指示这是权限问题还是缺少进程。

See man 2 killfor more info.

查看man 2 kill更多信息。

Also, if the process is your child, you can get a SIGCHLDwhen it dies, and you can use one of the waitcalls to deal with it.

另外,如果进程是你的子进程,你可以SIGCHLD在它死亡时得到一个,你可以使用其中一个wait调用来处理它。

回答by Egirus Ornila

With psutil you can check if a process id exists:

使用 psutil,您可以检查进程 ID 是否存在:

import psutil
print(psutil.pid_exists(1234))