Breaking the barrier of a broken paradigm... part 1

Discussion in 'Python' started by john s., Mar 25, 2008.

  1. john s.

    john s. Guest

    Hi Everyone,

    I hope not to offend you with too many question.. I've been lurking a
    long time. I'm not keen on keeping e-mails or data stored in the
    public space so this is my first post to the group.

    That being said, I'm keen on refining my skills, I hope that I can
    prove that I've move on beyond the: check the tut, read the faq..

    Now as it's out of the way I hope that my questions can be sited as
    examples for others breaking the procedural barrier.

    I've seen examples using reduce, map and lamba that cause me to emit a
    internal "WTFIZDISHI?"

    _____________________________

    With out any further adiou... IsMyKodeHotOrNot.... and how can I
    improve it... hopefully it will help me with part two...

    I'm sure anyone with 2 mins and solid skill of python can ballpark
    this one...


    _____________________________
    #/usr/bin/enviro python

    #Purpose - a dropped in useracct/pass file is on a new server to build
    a cluster... Alas there are no home #directories.. Let me rip through
    the passfile, grab the correct field (or build it) and use it to make
    the directory!

    import os, sys, string, copy, getopt, linecache
    from traceback import format_exception

    #The file we read in...
    fileHandle = "/etc/passwd"
    srcFile = open(fileHandle,'r')
    srcList = srcFile.readlines()

    #yah, a for loop that "iterates" through the file of "lines"
    for i in srcList:
    strUsr = string.split(i,":")
    theUsr = strUsr[0]
    usrHome = "/expirt/home/",theUsr,"/"
    usrHome = ''.join(usrHome)

    print "printing usrHome:",usrHome

    print "is it a dir?: ", os.path.isdir(usrHome)

    # try to test if it's a dir... for some reason this mis-behaves...
    maybe I'm not thinking about it correctly..

    if os.path.isdir(usrHome) != 'False':

    print "User Home dir doesn't exist creating."

    try:
    os.makedirs('usrHome' )
    except Exception, e:
    print e

    print "usrHome is: ",usrHome
    print "theUsr is: ",theUsr

    os.system('/usr/bin/chmod 750 ' + usrHome)
    os.system('/usr/bin/chown ' + theUsr + ' ' + usrHome)

    #OMG, there is directory that happens to already exist! well, due
    diligence and love for the queen dictates we #provide "due
    dilligence", (e.g. wipe our asses properly)

    else:
    print "User Home dir exist, checking and fixing permissions."

    print "usrHome is: ",usrHome
    print "theUsr is: ",theUsr

    os.system('/usr/bin/chmod 750 ' + usrHome)
    os.system('/usr/bin/chown ' + theUsr + ' ' + usrHome)

    #I know that I can't optimize the line below further... or... can I?

    sys.exit("Thanks for using pyDirFixr...")
     
    john s., Mar 25, 2008
    #1
    1. Advertising

  2. > On Behalf Of john s.
    > import os, sys, string, copy, getopt, linecache
    > from traceback import format_exception
    >
    > #The file we read in...
    > fileHandle = "/etc/passwd"
    > srcFile = open(fileHandle,'r')
    > srcList = srcFile.readlines()
    >
    > #yah, a for loop that "iterates" through the file of "lines"
    > for i in srcList:
    > strUsr = string.split(i,":")
    > theUsr = strUsr[0]
    > usrHome = "/expirt/home/",theUsr,"/"
    > usrHome = ''.join(usrHome)


    How about for starters:

    import os

    for line in open("/etc/passwd"):
    user, _pwd = line.split(":")
    user_home = os.path.join("/expirt/home", user)

    > try:
    > os.makedirs('usrHome' )
    > except Exception, e:
    > print e


    if os.path.exists(user_home):
    print "User Home dir exists, checking and fixing permissions."
    else:
    print "Do other stuff"

    Regards,
    Ryan Ginstrom
     
    Ryan Ginstrom, Mar 25, 2008
    #2
    1. Advertising

  3. john s.

    Bryan Olson Guest

    john s. wrote:

    > #/usr/bin/enviro python
    >
    > #Purpose - a dropped in useracct/pass file is on a new server to build
    > a cluster... Alas there are no home #directories.. Let me rip through
    > the passfile, grab the correct field (or build it) and use it to make
    > the directory!
    >
    > import os, sys, string, copy, getopt, linecache
    > from traceback import format_exception
    >
    > #The file we read in...
    > fileHandle = "/etc/passwd"
    > srcFile = open(fileHandle,'r')
    > srcList = srcFile.readlines()
    >
    > #yah, a for loop that "iterates" through the file of "lines"
    > for i in srcList:


    Convention is that the name i is for an integer.

    > strUsr = string.split(i,":")
    > theUsr = strUsr[0]
    > usrHome = "/expirt/home/",theUsr,"/"
    > usrHome = ''.join(usrHome)


    As Ryan noted, os.path is the favored way.


    > print "printing usrHome:",usrHome
    >
    > print "is it a dir?: ", os.path.isdir(usrHome)
    >
    > # try to test if it's a dir... for some reason this mis-behaves...
    > maybe I'm not thinking about it correctly..
    >
    > if os.path.isdir(usrHome) != 'False':


    That should always evaluate true. False != 'False'. I think you want:

    if not os.path.exists(usrHome):


    > print "User Home dir doesn't exist creating."
    >
    > try:
    > os.makedirs('usrHome' )
    > except Exception, e:
    > print e


    I don't think you want to catch the exception there. If creating the dir
    fails, the next bits of code should not execute.


    > print "usrHome is: ",usrHome
    > print "theUsr is: ",theUsr
    >
    > os.system('/usr/bin/chmod 750 ' + usrHome)
    > os.system('/usr/bin/chown ' + theUsr + ' ' + usrHome)
    >
    > #OMG, there is directory that happens to already exist! well, due
    > diligence and love for the queen dictates we #provide "due
    > dilligence", (e.g. wipe our asses properly)


    The path could exist but not be a directory.


    > else:
    > print "User Home dir exist, checking and fixing permissions."
    >
    > print "usrHome is: ",usrHome
    > print "theUsr is: ",theUsr
    >
    > os.system('/usr/bin/chmod 750 ' + usrHome)
    > os.system('/usr/bin/chown ' + theUsr + ' ' + usrHome)
    >
    > #I know that I can't optimize the line below further... or... can I?
    >
    > sys.exit("Thanks for using pyDirFixr...")


    Given the Unixy nature of your code, you probably want to sys.exit(0)
    for success and 1 or 2 for failure.

    Happy hacking,
    --
    --Bryan
     
    Bryan Olson, Mar 25, 2008
    #3
  4. john s.

    john s. Guest

    On Mar 24, 9:39 pm, "Ryan Ginstrom" <> wrote:
    > > On Behalf Of john s.
    > > import os, sys, string, copy, getopt, linecache
    > > from traceback import format_exception

    >
    > > #The file we read in...
    > > fileHandle = "/etc/passwd"
    > > srcFile = open(fileHandle,'r')
    > > srcList = srcFile.readlines()

    >
    > > #yah, a for loop that "iterates" through the file of "lines"
    > > for i in srcList:
    > > strUsr = string.split(i,":")
    > > theUsr = strUsr[0]
    > > usrHome = "/expirt/home/",theUsr,"/"
    > > usrHome = ''.join(usrHome)

    >
    > How about for starters:
    >
    > import os
    >
    > for line in open("/etc/passwd"):
    > user, _pwd = line.split(":")

    ^----- Ok this one here we are taking a string spliting it
    into to variables...
    user gets one (the first) and _pwd gets to hold the
    "leftovers"?

    > user_home = os.path.join("/expirt/home", user)
    >
    > > try:
    > > os.makedirs('usrHome' )
    > > except Exception, e:
    > > print e

    >
    > if os.path.exists(user_home):

    ^----- are(n't) exists and os.path.isadir
    interchangable?
    *nods in Bryan O. direction*

    > print "User Home dir exists, checking and fixing permissions."
    > else:
    > print "Do other stuff"
    >
    > Regards,
    > Ryan Ginstrom
     
    john s., Mar 25, 2008
    #4
  5. john s.

    john s. Guest

    On Mar 25, 6:34 am, Bryan Olson <> wrote:
    > john s. wrote:
    > > #/usr/bin/enviro python

    >
    > > #Purpose - a dropped in useracct/pass file is on a new server to build
    > > #a cluster... Alas there are no home directories.. Let me rip through
    > > #the passfile, grab the correct field (or build it) and use it to make
    > > #the directory!

    >
    > > import os, sys, string, copy, getopt, linecache
    > > from traceback import format_exception

    >
    > > #The file we read in...
    > > fileHandle = "/etc/passwd"
    > > srcFile = open(fileHandle,'r')
    > > srcList = srcFile.readlines()

    >
    > > #yah, a for loop that "iterates" through the file of "lines"
    > > for i in srcList:

    >
    > Convention is that the name i is for an integer.

    just a bit of silly walk on my part in the comment field...
    >
    > > strUsr = string.split(i,":")
    > > theUsr = strUsr[0]
    > > usrHome = "/expirt/home/",theUsr,"/"
    > > usrHome = ''.join(usrHome)

    >
    > As Ryan noted, os.path is the favored way.
    >
    > > print "printing usrHome:",usrHome
    > > print "is it a dir?: ", os.path.isdir(usrHome)
    > > #try to test if it's a dir... for some reason this mis-behaves...
    > > #maybe I'm not thinking about it correctly..

    >
    > > if os.path.isdir(usrHome) != 'False':

    >
    > That should always evaluate true. False != 'False'. I think you want:

    ok... yes I do

    >
    > if not os.path.exists(usrHome):
    > > print "User Home dir doesn't exist creating."
    > > try:
    > > os.makedirs(usrHome)
    > > os.system('/usr/bin/chmod 750 ' + usrHome)
    > > os.system('/usr/bin/chown ' + theUsr + ' ' + usrHome)
    > > except Exception, e:
    > > print e

    >
    > I don't think you want to catch the exception there. If creating the dir
    > fails, the next bits of code should not execute.

    ok. I see that now.

    >
    > > #OMG, there is directory that happens to already exist! well,
    > > #love for the queen dictates we provide "due
    > > #dilligence", (e.g. wipe our asses properly)

    >
    > The path could exist but not be a directory.


    So isadir is slightly better then exists?
    It felt like it was not working right...
    (probably because I was double testing the exp I see now)

    >
    > > else:
    > > print "User Home dir exist, checking and fixing permissions."
    > > sys.exit("Thanks for using pyDirFixr...")

    >
    > Given the Unixy nature of your code, you probably want to sys.exit(0)
    > for success and 1 or 2 for failure.

    got it. I'm guessing I'm better off with a last line print "g'bye"
    then sys.exit versus trying both at once...

    >
    > Happy hacking,
    > --
    > --Bryan

    Thanks Bryan :)
    -John
     
    john s., Mar 25, 2008
    #5
  6. john s.

    Paul McGuire Guest

    This code is SO *CUTE*! I wish there was a font with little hearts to
    dot the 'i's with, then it would be PERFECT!
     
    Paul McGuire, Mar 25, 2008
    #6
  7. En Tue, 25 Mar 2008 07:44:59 -0300, john s. <>
    escribió:

    >> for line in open("/etc/passwd"):
    >> user, _pwd = line.split(":")

    > ^----- Ok this one here we are taking a string spliting it
    > into to variables...
    > user gets one (the first) and _pwd gets to hold the
    > "leftovers"?


    No; if the line contains more than a single : that code will fail.
    user, remainder = line.split(":", 1)

    With Python 3.0 you could write:
    user, _pwd, *other = line.split(":")
    but limiting the number of splits is more efficient if you are not
    interested in the remaining list. A more interesting case is:
    a, b, *other, c = line.split(":")
    to obtain the first, second and last items.

    --
    Gabriel Genellina
     
    Gabriel Genellina, Mar 25, 2008
    #7
  8. john s. a écrit :
    > On Mar 24, 9:39 pm, "Ryan Ginstrom" <> wrote:
    >>> On Behalf Of john s.
    >>> import os, sys, string, copy, getopt, linecache
    >>> from traceback import format_exception
    >>> #The file we read in...
    >>> fileHandle = "/etc/passwd"
    >>> srcFile = open(fileHandle,'r')
    >>> srcList = srcFile.readlines()
    >>> #yah, a for loop that "iterates" through the file of "lines"
    >>> for i in srcList:
    >>> strUsr = string.split(i,":")


    Erroneous hungarian notation is Bad(tm). And FWIW, the convention is to
    use all_lower for variable names.

    (snip consideration about using str.methods instead of string functions
    etc...)

    >> How about for starters:
    >>
    >> import os
    >>
    >> for line in open("/etc/passwd"):


    NB : this idiom relies on the VM automatically closing files, which is
    not garanteed on each and every implementation (IIRC, jython won't do
    it). This is ok for Q&D throwaway scripts targeting CPython, but should
    not go into production code.

    >> user, _pwd = line.split(":")

    > ^----- Ok this one here we are taking a string spliting it
    > into to variables...
    > user gets one (the first) and _pwd gets to hold the
    > "leftovers"?


    Quite. user gets the first, _pwd gets the second. If you have more than
    2 fields (IOW : more than one ':') in the line, it will raise.

    If you want to make sure this will still work with more than 2 fields,
    you can use the optional max_split arg:

    user, rest = line.split(':', 1)

    >> user_home = os.path.join("/expirt/home", user)
    >>
    >>> try:
    >>> os.makedirs('usrHome' )
    >>> except Exception, e:


    Better to be as specific as possible wrt/ exceptions you want to handle.
    Remember that some exceptions are better left alone (hint: sys.exit
    works by raising an exception...)

    >>> print e

    >> if os.path.exists(user_home):

    > ^----- are(n't) exists and os.path.isadir
    > interchangable?


    They're not. If you want to be bulletproof, you'll have to use
    os.path.isdir *and* handle the case where user_home exists and is not a
    directory.


    HTH
     
    Bruno Desthuilliers, Mar 25, 2008
    #8
  9. > On Behalf Of Bruno Desthuilliers
    > >> for line in open("/etc/passwd"):

    >
    > NB : this idiom relies on the VM automatically closing files,
    > which is not garanteed on each and every implementation
    > (IIRC, jython won't do it). This is ok for Q&D throwaway
    > scripts targeting CPython, but should not go into production code.


    You're right. For production, I'd probably do this.

    def create_user_dirs(lines):
    for line in lines:
    pass # process lines here

    with open("/etc/passwd") as fp:
    create_user_dirs(fp)

    This has the benefit of allowing me to test create_user_dirs without
    touching the file system (by passing in a list of lines).

    Regards,
    Ryan Ginstrom
     
    Ryan Ginstrom, Mar 25, 2008
    #9
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Amy
    Replies:
    0
    Views:
    543
  2. Dmitriy V'jukov
    Replies:
    11
    Views:
    629
  3. Ant
    Replies:
    28
    Views:
    799
    Lie Ryan
    Sep 26, 2010
  4. Ilias Lazaridis
    Replies:
    8
    Views:
    223
    Ilias Lazaridis
    May 19, 2011
  5. Ilias Lazaridis
    Replies:
    7
    Views:
    193
    Ilias Lazaridis
    Jun 4, 2011
Loading...

Share This Page