且构网

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

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

更新时间:2023-11-26 09:05:40

此答案建立在 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.')