portable fortune program

J.Jacob joost_jacob at hotmail.com
Sat Apr 27 12:57:34 EDT 2002


I have always liked the unix fortune program.
Unfortunately nowadays some *n.x's come without fortune,
and sometimes I have to work with Windows.  I wanted to be
able to do:
    C:\mydirectory> python -c "import fortune; fortune.quote()"
printing a nice quote to stdout.
The fortune module has to be able to locate a file with
the name 'allfortunes'.  And you want everything to be
portable.  And working with python 1.5.2 too.

The allfortunes file contains quotes separated by lines
with a '%' as its first character.  I downloaded a couple
of BSD fortune files and combined them into allfortunes.
If you put the following fortune.py file with an
allfortunes file into one of the directories in your
sys.path, or in you current working directory, it will work.

This is a first hack, it is slow, the allfortunes file is
not compressed, so comments are welcome, maybe you can
suggest improvements?  I was trying to put the allfortunes
file into a compressed string at the end of the fortune.py
file, so you do not need a separate file anymore, but I
did not see a best way to do it.  Please let me know if it
does not work with your python distribution.

joost_jacob at hotmail.com



# file fortune.py
import random, os

def randlistindex(yourlist):
    "Return a random index number into yourlist"
    return random.randint(0, len(yourlist)-1)

def quote():
    """
    Return a quote <string> from file allfortunes,
    assume the file allfortunes is located in the same
    directory as this module."""
    datafile = os.path.join(
      os.path.dirname(__import__(__name__).__file__),
      'allfortunes' )
    quotesfile = open(datafile)
    quoteslist, quote = [], ''
    for s in quotesfile.readlines():
        if s[0] == '%':
            if quote:
                quoteslist.append(quote)
                quote = ''
        else: quote = quote + s
    if quote: quoteslist.append(quote)
    print quoteslist[randlistindex(quoteslist)],



More information about the Python-list mailing list