Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #11570 > unrolled thread

Re: Linux : create a user if not exists

Started byTerry Reedy <tjreedy@udel.edu>
First post2011-08-16 11:52 -0400
Last post2011-08-16 11:52 -0400
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: Linux : create a user if not exists Terry Reedy <tjreedy@udel.edu> - 2011-08-16 11:52 -0400

#11570 — Re: Linux : create a user if not exists

FromTerry Reedy <tjreedy@udel.edu>
Date2011-08-16 11:52 -0400
SubjectRe: Linux : create a user if not exists
Message-ID<mailman.75.1313510107.27778.python-list@python.org>
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

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web