Re: Newbie: executing a system command from my Python app



Dan M wrote:
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.

Few points points:

1. Generally: I would try to minimize system calls. They make your code less
   portable.
2. Look into the "shutil" module for recursive deletion.
3. Use os.path to construct paths. Try to avoid, for example,
   "c:\blah\blah" on dos, '/blah/blah' on unix, etc.
4. If you only have one argument, you don't need a tuple for string formatting.
5. "(dateYest)" is not a tuple anyway--the parentheses are superfluous
6. Single item tuples can be created with "(anitem,)" (notice the comma).

James
.



Relevant Pages


Loading