newbie playing with glob

Steve Holden sholden at holdenweb.com
Thu Jan 17 16:48:02 EST 2002


"Andrew Replogle" <replogle992 at hotmail.com> wrote ...
> Hello,
>
>  I am a python newbie and this language looks really cool. I have no
> previous programming experience and this is where I'd like to start.
> What I am currently doing is writing little programs for small unix
> administration tasks. I'm stuck on one of these programs.
>
We all get stuck from time to time. Welcome to comp.lang.python!

> I'm trying to create a .forward in every home directory on the system.
> Here's what I've been using:
>
> import os, sys, glob
>
> for file in glob.glob('/home//*//*'):
>     os.exec(touch file/.forward)
>
> and I've tried a couple combinations with no luck.. any insight would
> greatly be appreciated.
>
Your first confusion appears to be with string escape sequences, which use
*backslashes*, so the good news is you probably don't need them here. I'm
assuming the typical home directory is something like "/home/admin/steve" ?

You can make sure you've got the globbing right with something like

    for file in glob.glob("/home/*/*"):
        print file

before you go on to finer things. The next misconception is using os.exec.
Like the C library, exec() will replace the running promgram image with
something else. Fortunately a) there is no exec (though you'll find execl,
execv, and many others) and b) even if there were, they expect string
arguments.

You *might* want to use os.system(), which is effectively like running a
command in a subshell. You might then try:

    for file in glob.glob("/home/*/*"):
        os.system("touch "+file+"/.forward")

and this would probably work (I haven't tested it). But hey, this is Python,
it can create text files. So you might also write:

    for file in glob.glob("/home/*/*"):
        open(file+"/.forward", "w")

and this (though again untested) would probably also work.

Then you can go on to extracting the user name from the directory, and
changing the ownership of the .forward files. You're right, Python *is*
neat,and I know you're going to have a bundle of fun. Just remember to help
other newbies as your skill grows.

There are more elegant ways of doing some of the things we've discussed, but
elegance takes second place to practicality in the sys admin world. Good
luck!

regards
 Steve
--
Consulting, training, speaking: http://www.holdenweb.com/
Python Web Programming: http://pydish.holdenweb.com/pwp/








More information about the Python-list mailing list