[Tutor] random file rotation program

antonmuhin at rambler.ru antonmuhin at rambler.ru" <antonmuhin@rambler.ru
Wed Mar 26 12:34:02 2003


Hello Kirk,

Friday, June 7, 2002, 8:18:16 AM, you wrote:

KDB> OK, I have used a program in C to rotate banners and 'fortunbe cookies'
KDB> for a lonmg time, but I just took a stab at writing one in python to do
KDB> it for me. Here is my first jab at it.

KDB> #!/usr/local/bin/python
KDB> # the previous line MUST be the first line, and MUST point at your
KDB> server's
KDB> # python interpeter!
KDB> #
KDB> # cookie.py (C)2002 Kirk D Bailey
KDB> # Released under the GNU GPL.
KDB> #
KDB> import os.path, string, sys, random
KDB> #
KDB> # targetfile = sys.argv[1] try this later when basic is working.
KDB> targetfile='cookiejar'
KDB> #
KDB> #----v----1---v----2---v---3----v----4----v----5----v----6----v----7----v----8

KDB> #
KDB> # use this next line if you are using ssi with the 'include' tag.
KDB> # if you use the 'exec' tag, comment out the next line.
KDB> print "content-type: text/html\n\n"
KDB> #
KDB> # invoke in a web page as:
KDB> # <!-- include virtual="/cgi-bin/cookie.py" -->
KDB> #
KDB> print '<!-- random cookie by COOKIE.PY -->'
KDB> print '<!-- from http://www.tinylist.org -->'
KDB> #
KDB> def gangstrip(thing):                   # ok, everybody STRIP!
KDB>     index=0                                # This strips out whitespace
KDB> chars
KDB>     while index < len(thing):      # define exit
KDB>         thing[index]=string.strip(thing[index])
KDB>         index=index+1  # increase the counter
KDB>     return thing
A little bit unpythonic for me. I'd put it:

thing = [s.strip() for s in thing]

KDB> #
KDB> if os.path.exists(targetfile):
KDB>     f1.open(targetfile,'r')
KDB>     cookies=gangstrip(f1.readlines())
KDB>     f1.close()
KDB> else
KDB>     cookies = ['ERROR:file "' + targetfile + '" not found or
KDB> unavailable.']
It seems (although I didn't check), that it could be written with
exceptions:

try:
    f = file(targetfile, 'r')
    cookies = [line.strip() for line in f]
    f.close()
except:
    cookies = ['ERROR:file "' + targetfile + '" not found or unavailable.']

Defenitely, it's far from ideal, but for quick'n'dirty script...

KDB> #
KDB> print random.choice(cookies)










-- 
Best regards,
 anton                            mailto:antonmuhin@rambler.ru