如何使用 Python 检查 GNU/Linux 操作系统中是否存在用户?

如何使用 Python 检查 GNU/Linux 操作系统中是否存在用户?

问题描述:

使用 Python 在 GNU/Linux 操作系统上检查用户是否存在的最简单方法是什么?

What is the easiest way to check the existence of a user on a GNU/Linux OS, using Python?

有什么比发出 ls ~login-name 并检查退出代码更好的方法了吗?

Anything better than issuing ls ~login-name and checking the exit code?

如果在 Windows 下运行?

And if running under Windows?

此答案建立在 Brian 的答案 之上.它添加了必要的 try...except 块.

This answer builds upon the answer by Brian. It adds the necessary try...except block.

检查用户是否存在:

import pwd

try:
    pwd.getpwnam('someusr')
except KeyError:
    print('User someusr does not exist.')

检查组是否存在:

import grp

try:
    grp.getgrnam('somegrp')
except KeyError:
    print('Group somegrp does not exist.')