[Tutor] send os.system() output to tarfile?
dkuhlman at rexx.com
Tue Aug 7 23:50:35 CEST 2007
On Tue, Aug 07, 2007 at 03:55:03PM -0400, Brian Jones wrote:
> I'm currently writing a script to backup a mysql database. On the cli, I'd
> do something like this:
> 'mysqldump dbname | gzip -9 > dbname-date.gz'
> Note that "gzip -9" could just as easily be "tar cvzf" for example.
> Anyway, what I'm trying to do is figure out the right way to redirect the
> output generated by "os.system(mysqldump dbname)" to my tarfile object for
> compressing. What I tried were a few variations on this:
> #!/usr/bin/env python
> import os
> import time
> import tarfile
> import sys
> filename = time.strftime("%Y%m%d") + ".tgz"
> tarball = tarfile.open(filename, "w|gz", fileobj = sys.stdout)
> os.system( "ls -alrt" )
I'm not sure why you are are not doing something like this:
cmd = 'mysqldump %s | gzip -9 > %s-%s.gz' % (dbname, dbname, date, )
But, if you want more control, then look at these functions/modules
in the Pyhon standard library:
- popen, popen2, etc -- http://docs.python.org/lib/os-process.html
- tarfile -- http://docs.python.org/lib/module-tarfile.html
popen will enable you to capture the output from your command. Use
one of the other popenX functions if you need to capture both
stdout and stderr.
tarfile will enable you to stuff that captured output into a tar.gz
Also, see the zipfile module if you want to save into a zip file.
With tarfile, you may have to write data to a temp file and then
archive that. With zipfile, you can write content directly into a
zipfile. Is there a way around this?
More information about the Tutor