目前我正在使用 pwd.getpwall(),它显示了整个密码数据库。但我只想要计算机的用户帐户。使用 getpwall() 我无法做到这一点......
if 'foo' in pwd.getpwall():
do stuff
因为 pwd.getpwall() 返回一个对象列表。如果我想检查用户是否存在,我将不得不执行一个循环。我认为有一种更简单的方法可以做到这一点。
最佳答案
在the same page of the manual :
pwd.getpwnam(name)
Return the password database entry for the given user name.
这是存在和不存在用户的结果:
>>> import pwd
>>> pwd.getpwnam('root')
pwd.struct_passwd(pw_name='root', pw_passwd='*', pw_uid=0, pw_gid=0, pw_gecos='System Administrator', pw_dir='/var/root', pw_shell='/bin/sh')
>>> pwd.getpwnam('invaliduser')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'getpwnam(): name not found: invaliduser'
因此你可以这样做:
try:
pwd.getpwnam(name)
except KeyError:
# Handle non existent user
pass
else:
# Handle existing user
pass
注意:无论如何,in
运算符都会执行一个循环来检查给定的项目是否在列表 (ref) 中。
关于python - 有没有一种干净的方法可以通过 python 检查计算机上是否存在给定用户?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6916208/