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

Bryan Olson fakeaddress at nowhere.org
Tue Mar 25 06:34:19 EDT 2008


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



More information about the Python-list mailing list