[Tutor] string formatting

Mark Lawrence breamoreboy at yahoo.co.uk
Wed Oct 24 23:16:05 CEST 2012

On 24/10/2012 21:11, Mike wrote:
> I'm in the process of learning python and migrating away from bash
> scripting. I'm in the process of converting my bash scripts that
> essentially ssh to another host via shared keys, execute commands
> remotely, and exit. To do this I started using paramiko but eventually
> decided to do it w/ subprocess since I am more familiar with that as a
> result of me converting other scripts.
> This is what I'm currently working on, the purpose of this is to ssh
> into another machine, make a tarball of dumped .sql files, save the
> tarball with the result of timestamp() as the naming convention, then it
> will eventually clean it up based on file age:
> http://dpaste.com/817874/
> This is the result after executing the script:
> rev at omega:~/code/beavis/test$ ls
> bleh1.sql  bleh2.sql  bleh3.sql  ssh-jobs.py
> rev at omega:~/code/beavis/test$ ./ssh-jobs.py
> tar: Removing leading `/' from member names
> /home/rev/code/beavis/test/bleh2.sql
> /home/rev/code/beavis/test/bleh3.sql
> tar: /home/rev/code/beavis/test/24.10.2012: Cannot stat: No such file or
> directory
> tar: 15\:06\:52.tgz: Cannot stat: No such file or directory
> tar: Exiting with failure status due to previous errors
> rev at omega:~/code/beavis/test$
> As you can see it looks like its having issues with the way I'm using
> timestamp() for string formatting, as far as I can tell it is not a tar
> specific problem? Any help/insight on this would be greatly appreciated.

You might as well have put your code inline, so here it is before it 
expires, poor code :(

#!/usr/bin/env python
import subprocess,time

# Start with the basics.
hostTarg = "localhost"
dirTarg = "/home/rev/code/beavis/test"
fileTarg = "/home/rev/code/beavis/test/*.sql"

def timestamp():
     lt = time.localtime(time.time())
     return "%02d.%02d.%04d %02d:%02d:%02d" % (lt[2], lt[1], lt[0], 
lt[3], lt[4], lt[5])

package = "tar zcvf %s %s/%s.tgz" % (fileTarg, dirTarg, timestamp())
clean = "find  %s -type f -mtime +6 -exec rm {} \;" % dirTarg

def process():
     subprocess.call(["ssh", hostTarg, package])


I'd use http://docs.python.org/library/time.html#time.strftime to do the 
timestamp formatting and put some print statements into the code so you 
know what's going on.  Having said that it looks as if it's barfed on 
the first colon.  I'll soon get corrected if I'm wrong :)


Mark Lawrence.

More information about the Tutor mailing list