Newbie Question: Shell-like Scripting in Python?

Michael Stenner mstenner at phy.duke.edu
Tue Oct 1 23:12:06 EDT 2002


On Tue, Oct 01, 2002 at 07:54:07PM -0700, Scott Meyers wrote:
> I'm an experienced programmer, but I'm new to Python.  I'm working my way
> through "Learning Python," and that's fine.  One of the things I want to do
> is parse mp3 files and edit their ID3 tags, but I know that I must crawl
> before I can run, and I'm happy to jog up the learning curve before trying
> to parse binary files.  (I also know that a bunch of ID3 editing programs
> already exist.  I just think it'd be a good learning exercise.)

I don't know the format, but you probably want to look at the "struct"
module.  It is made for packing and unpacking binary data.

> Another thing I want to do is write short shell-like scripts for my Windows
> machine, e.g., copy and move or rename files whose size fulfills some
> criteria or whose name matches some regexp, etc.  One of the reasons I
> decided to play with Python was that I thought it could do these
> scripting-like things; the first sentence on the back of "Learning Python"
> refers to its suitability for "quick scripts."  However, I haven't seen
> anything in the book's TOC or index on shell-like scripts, and a cursory
> scan of the info at www.python.org didn't show any examples of things like
> manipulating the underlying file system in a shell-script like manner.  So
> here's my question: will Python let me do that?  I'm not asking about how
> powerful the language is -- I know I can do anything with it.  But suppose
> I want to rename files matching foo.* to be bar.*.  Ideally, I'd like to be
> able to say something like this:
> 
>   rename foo.* bar.*
> 
> Will Python let me do that kind of thing?  If so, great.  If not, that's
> okay, too.  At this point, I'm just trying to set my expectations
> correctly.

Writing a script to do that should be very easy.  A couple of notes:
check out the "shutils", "os", and "os.path" modules.  Possibly also
"re", "fnmatch", and "glob".  

The only troublesome thing I see here is that "foo.*" is going to be
expanded by the shell (I think this is true for dos also) before your
program ever gets it.  So if you have the files foo.exe, foo.bat,
bar.cab, then as you wrote it, your program will see:

> print sys.argv[1:]
['foo.exe', 'foo.bat', 'bar.cab']

So you'll probably need to quote the filenames on the command line (or
come up with your own matching language that doesn't overlap with
normal globbing... icky).

rename "foo.*" "bar.*"

> print sys.argv[1:]
['foo.*', 'bar.*']

(at least that's how it works on unix -- I think it's the same in dos)

					-Michael

-- 
  Michael Stenner                       Office Phone: 919-660-2513
  Duke University, Dept. of Physics       mstenner at phy.duke.edu
  Box 90305, Durham N.C. 27708-0305




More information about the Python-list mailing list