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

J

john s.

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...")
 
R

Ryan Ginstrom

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
 
B

Bryan Olson

john said:
#/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,
 
J

john s.

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)


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

john s.

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):

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.
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)
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,
Thanks Bryan :)
-John
 
P

Paul McGuire

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!
 
G

Gabriel Genellina

^----- 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.
 
B

Bruno Desthuilliers

john s. a écrit :
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...)

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.
^----- 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)

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...)
^----- 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
 
R

Ryan Ginstrom

On Behalf Of Bruno Desthuilliers
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
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,969
Messages
2,570,161
Members
46,705
Latest member
Stefkari24

Latest Threads

Top