2024-05-14 05:52:28 发布
网友
目前我正在使用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.
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'
因此,您可以:
注意:in运算符无论如何都会执行一个循环来检查给定的项是否在列表(ref)中。在
in
如果用户不存在,pwd.getpwnam引发一个KeyError:
pwd.getpwnam
KeyError
def getuser(name): try: return pwd.getpwnam(name) except KeyError: return None
您可以使用类似于:
>>> [x.pw_name for x in pwd.getpwall()]
存储列表并检查username in list
username in list
在the same page of the manual:
这是现有用户和不存在用户的结果:
因此,您可以:
^{pr2}$注意:
in
运算符无论如何都会执行一个循环来检查给定的项是否在列表(ref)中。在如果用户不存在,
pwd.getpwnam
引发一个KeyError
:您可以使用类似于:
存储列表并检查
username in list
相关问题 更多 >
编程相关推荐