如何使用 Python 检查 GNU/Linux 操作系统中是否存在用户? [英] How to check if a user exists in a GNU/Linux OS using Python?

查看:53
本文介绍了如何使用 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.') 

这篇关于如何使用 Python 检查 GNU/Linux 操作系统中是否存在用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆