Newbie: executing a system command from my Python app

Dan M dan at wolf.com
Mon Dec 12 16:25:14 EST 2005


I'm writing a Python replacement for a particularly ugly shell script. we
are running mimedefang on our mail server, moving spam and virus messages
to a quarantine directory. This little python script successfully chdir's
to the quarantine directory, identifies all of the quarantine
subdirectories for yesterday's messages, and stuffs them into a tar file
in an archive directory. I then want to delete for successfully tarred
files and the subdirs they live in.

By way of further explanation, quarantined messages get broken into files
named ENTIRE_MESSAGE, HEADERS, RECIPIENTS, SENDER, and SENDMAIL-QID, and
get stored in subdirectories named qdir-YYYY-MM-DD-hh.mm.ss-nnn, where
Y-M-D is the date received, hms is time received, and nnn is to allow for
up to 10 messages to quarantined any given second.

I know I can do this by descending into the directories I've identified
and unlink()ing each of the files, but I'd like to take a shortcut like:
"retval = os.system('rm -rf /var/spool/MD-Quarantine/qdir-%s*' %
(dateYest))" and indeed code written that executes without any errors.
Unfortunately it also leaves a bunch of qdir-2005-12-11-* files sitting
around when I run it on 12-11.

Have I overlooked some basic operation of the os.system() call? From all
I've seen in the online docs and O'Reilly's "Programming Python" it looks
like it should be working.

Here's my complete script:
#!/usr/local/bin/python

import glob, os, tarfile, time, datetime
DATE_FMT = "%Y-%m-%d"
filelist = []

yest = datetime.date.today() + datetime.timedelta(days = -1)
dateYest = yest.strftime(DATE_FMT)

os.chdir("/var/spool/MD-Quarantine")

try:
        tar = tarfile.open("/usr/local/archives/MD-Q/%s.tar.gz" % (dateYest), "w:gz")
        for file in glob.glob("qdir-%s*" % (dateYest)):
                tar.add(file)
                filelist.append(file)
        tar.close()
except TarError:
        print "The quarantine file archiving program threw a TarError exception"        exit()

cmd = "rm -rf /var/spool/MD_Quarantine/qdir-%s*" % (dateYest)
print "About to execute ", cmd
retval = os.system(cmd)




More information about the Python-list mailing list