CrunchBang Linux Pastebin - collaborative debugging

pastebin is a collaborative debugging tool allowing you to share and modify code snippets while chatting on IRC, IM or a message board.

This site is developed to XHTML and CSS2 W3C standards. If you see this paragraph, your browser does not support those standards and you need to upgrade. Visit WaSP for a variety of options.

CrunchBang Linux Pastebin

Difference between
modified post 378 by benj1 on Tue 3rd Nov 10:08 and
original post 377 by benj1 on Mon 2nd Nov 22:36
Show old version | new version | both versions

    
11
#! /usr/bin/env python
22
#
33
# Author: Ben Holroyd <holroyd.ben@gmail.com>
44
# License: GPL 3.0+
55
#
66
# Usage:
77
# Put an entry in ~/.config/openbox/menu.xml:
88
# <menu id="Listing" label="listing" execute="~/.config/openbox/scripts/tvlisting" />
99
#called without args just checks that listings are up to date for that day
1010
#-t prints in plain text to stdout
1111
#-p is for use in pipe menus
1313
from HTMLParser import HTMLParser
1414
from urllib import FancyURLopener
1515
from threading import Thread
1616
import datetime,os
1717
from optparse import OptionParser
1919
#dict of channels with channel codes, need to get from radio times website
2020
channellistdict = {'BBC1':'92','BBC2':'105','ITV':'26','Channel4':'132','Five':'134'}
2121
#need a separate list, as dict gets out of order
2222
channellist=['BBC1','BBC2','ITV','Channel4','Five']
2323
#where temporary files are kept
2424
tmpfile = "/tmp"
2626
#dont touch
2727
tmpfile=os.path.join(tmpfile,"%%s-%s" % datetime.date.today())
2828
address="http://www.radiotimes.com/ListingsServlet?event=4&jspGridLocation=%%2Fjsp%%2Ftv_listings_grid.jsp&jspListLocation=%%2Fjsp%%2Ftv_listings_single.jsp&jspError=%%2Fjsp%%2Ferror.jsp&listingsFormat=L&channels=%s"
30-
class parser(HTMLParser):
30+
class pageparser(HTMLParser):
3131
    def __init__(self, data, channel):
3232
        """parse downloaded pages, and save by channel in tmp"""
3333
        HTMLParser.__init__(self)
3434
        self.bltime = False
3535
        self.bltitle = False
3636
        self.time = ''
3737
        #hack-- htmlparser doesnt like original form, even though its in comments
3838
        data = data.replace("</scr'+'ipt>","</script>")
3939
        self.file = open(tmpfile % channel, 'w')
4040
        self.feed(data)
4242
    def handle_starttag(self, tag, attrs):
4343
        if tag == 'p' and attrs:
4444
            if attrs[0][1] == 'startTime':
4545
                self.bltime = True
4646
            if attrs[0][1] == 'progTitle':
4747
                self.bltitle = True
4949
    def handle_data(self,data):
5050
        if self.bltime == True:
5151
            self.time = data
5252
            self.bltime = False
5353
        if self.bltitle == True:
5454
            self.file.write('%s%%%s\n' % (data, self.time))
5555
            #print "Title: ",data, 'time: ', self.time
5656
            self.bltitle = False
5858
class downloader(Thread):
5959
    """threaded downloader for webpages"""
6060
    def __init__ (self, url, channelcode, channel):
6161
        Thread.__init__(self)
6262
        self.channel = channel
6363
        self.channelcode = channelcode
6464
        self.url = url
6666
    def run(self):
6767
        try:
6868
            data = FancyURLopener().open(self.url % self.channelcode).read()
6969
        except IOError:
7070
            pass
71-
        parser(data, self.channel)
71+
        pageparser(data, self.channel)
7373
class printer():
7474
    """print parsed files"""
7575
    def __init__(self, channel):
7676
        self.now = datetime.datetime.now()
7777
        self.channel = channel
7878
        #check we have listings for the correct day
7979
        if not os.path.exists(tmpfile % self.channel):
8080
            downloader(address,channellistdict[self.channel],self.channel).start()
8282
        file = open(tmpfile % self.channel, 'r').read()
8383
        data = [line.split('%') for line in file.split('\n') if len(line) > 0]
8484
        #find most recent program, then trim 'data' to fit.
8585
        for index, [programme, time] in enumerate(data):
8686
            if self.comparetime(time):
8787
                if index == 0: index = 1 #just in case a programme starts just before midnight
8888
                self.data = data[index-1:]
8989
                break
9191
    def comparetime (self,cmp_time):
9292
        """returns true if time supplied is bigger than current time"""
9393
        hour, minute = self.now.hour, self.now.minute
9494
        #converts 'hh:mm a/pm' to int, pam strips pm and am from string
9595
        cmp_hour,cmp_minute = map(int, cmp_time.rstrip('pam').split(':'))
9696
        #convert to 24hr time, & sort 12am, 12pm
9797
        if cmp_time.endswith('pm') and cmp_hour != 12: cmp_hour += 12
9898
        if cmp_time.endswith('am') and cmp_hour == 12: cmp_hour -= 12
9999
        return (cmp_hour, cmp_minute) > (hour, minute)
101101
    def showxmlmenu(self):
102102
        print "  <menu id=\"%s\" label=\"%s\">" % (self.channel,self.channel)
103103
        print "    <item label=\"Now: %s %s\"/>" % (self.data[0][0],self.data[0][1])
104104
        print "    <item label=\"Next: %s %s\"/>" % (self.data[1][0],self.data[1][1])
105105
        print "    <menu id=\"Then%s\" label=\"Then\">" % (self.channel)
106106
        for programme, time in self.data[2:]:
107107
            print "      <item label=\"%s (%s)\"/>" % (programme,time)
108108
        print "    </menu>"
109109
        print "  </menu>"
111111
    def showplaintext(self):
112112
        for programme, time in self.data:
113113
            print programme, ' Starts: ', time
115115
parser = OptionParser(
116116
    version=" %prog V0.1 Ben Holroyd",
117117
    description = "%prog - print tv listings, if called without options will check\nthat the listings are upto date and redownload if needed",
118118
    usage = "%prog [-tp] [--text] [--pipe] [--help]")
119119
parser.add_option("-t", "--text", action="store_true", dest="text", default=False, help="print tvlistings in plain text")
120120
parser.add_option("-p", "--pipe", action="store_true", dest="pipe", default=False, help="print listings in xml suitable for obmenu")
121121
(options, args) = parser.parse_args()
123123
for entry in channellist: #check files are up to date
124124
    if not os.path.exists(tmpfile % entry):
125125
        downloader(address,channellistdict[entry],entry).start()
127127
if options.text:
128128
    for entry in channellist:
129129
        print "\n\033[01;04m%s\033[00;00m" % entry #print bold & underlined
130130
        printer(entry).showplaintext()
132132
elif options.pipe :
133133
    print "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
134134
    print "<openbox_pipe_menu>"
135135
    for entry in channellist: printer(entry).showxmlmenu()
136136
    print "</openbox_pipe_menu>"

Syntax highlighting:

To highlight particular lines, prefix each line with @@


Remember me