Linux : create a user if not exists

Terry Reedy tjreedy at udel.edu
Tue Aug 16 11:52:13 EDT 2011


On 8/16/2011 10:57 AM, smain kahlouch wrote:
> Ok than you. You're right but it doesn't help me :
> I replaced it :
>
>  >>> def finduser(user):
> ...     if pwd.getpwnam(user):
> ...             print user, "user exists"
> ...             return True
> ...     return False
> ...
>  >>> finduser('realuser')
> realuser user exists
> True
>  >>> finduser('blabla')
> Traceback (most recent call last):
>    File "<stdin>", line 1, in ?
>    File "<stdin>", line 2, in finduser
> KeyError: 'getpwnam(): name not found: blabla'
>
> As you can see, i just want to look for a user and if it doesn't exist,
> an action is taken (create user).

Replace if/then with try/except control flow

try:
    pwd.getpwnam(user)
    return True
except KeyWordError:
    return False

-- 
Terry Jan Reedy




More information about the Python-list mailing list