Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #Horaires RATP for MetronomeBus v0.5
- #Copyright <copyright>
- #
- #Permission is hereby granted, free of charge, to any person obtaining a copy of
- #this software and associated documentation files (the "Software"), to deal in
- #the Software without restriction, including without limitation the rights to
- #use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
- #of the Software, and to permit persons to whom the Software is furnished to do
- #so, subject to the following conditions:
- #The above copyright notice and this permission notice shall be included in all
- #copies or substantial portions of the Software.
- #
- #The Software is provided "as is", without warranty of any kind, express or
- #implied, including but not limited to the warranties of merchantability,
- #fitness for a particular purpose and noninfringement. In no event shall the
- #authors or copyright holders be liable for any claim, damages or other
- #liability, whether in an action of contract, tort or otherwise, arising from,
- #out of or in connection with the software or the use or other dealings in the
- #Software.
- #
- # </copyright>
- # <author>Antoine FERRON</author>
- # <date>2012-16-04</date>
- # <summary>Affiche les horaires aux arrets de la RATP</summary>
- # Based On: Script RATP by Gawel (Gael Pasgrimaud) : hg.gawel.org/ratp/
- #
- # usage : [ -l <lineid> station name ]
- #
- # Compiled with : Python 2.7.3, PyWin32 2.1.7, PyInstaller 1.5.1
- # -*- coding: utf-8 -*-
- import re
- import os
- import sys
- import time
- import urllib2
- import httplib
- import logging as log
- from datetime import datetime
- from optparse import OptionParser
- def debug(func):
- def wrapper(*args, **kwargs):
- result = func(*args, **kwargs)
- log.debug('%s(*%r, **%r) -> %s', func.func_name, args[1:], kwargs, result)
- return result
- return wrapper
- entities = (
- ('</', ''),
- ('é', 'e'),
- ('è', 'e'),
- ('â', 'a'),
- ('ô', 'o'),
- )
- def clean_html(data):
- if data.startswith('<b>'):
- data = data.replace('<b>', '').replace('</b>', '')
- for a, b in entities:
- data = data.replace(a, b)
- return data
- class Service(object):
- def __init__(self):
- self.headers = {
- 'User-Agent': 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; fr; rv:1.9.2) Gecko/20100115 Firefox/3.6',
- }
- self.conn = httplib.HTTPConnection("wap.ratp.fr")
- def open(self, path, **kwargs):
- self.conn.request("GET", path , '', self.headers)
- resp = self.conn.getresponse()
- return resp
- @debug
- def post(self, path='', **kwargs):
- resp = self.open(path)
- self.headers['referer'] = 'http://www.ratp.fr%s' % path
- data = resp.read()
- if 'body' in data:
- data = data.split('<body>')[1]
- data = data.replace('div', '\n')
- data = data.replace('\n > ', '<b>')
- data = re.findall('.*class="(?:bg|schmsg)(?:[0-9]+)">(.*)', data)
- data = [clean_html(d) for d in data if d[:3] in ('<b>')]
- return data
- def close(self):
- self.conn.close()
- def get(self,**kwargs):
- kwargs['reseau'] = kwargs.get('lineid')[0] == 'M' and 'metro' or 'bus'
- kwargs['stationname'] = kwargs['station'].replace(' ', '+')
- url = '/siv/schedule?service=next'
- url += '&reseau=%(reseau)s&referer=station&lineid=%(lineid)s' % kwargs
- url += '&directionsens=%(directionsens)s' % kwargs
- url += '&stationname=%(stationname)s&submitAction=Valider' % kwargs
- data = self.post(url)
- output = []
- while data:
- if len(data) == 1:
- output.append(' '+data.pop())
- if len(data) > 1:
- if data[0].startswith("INFO INDISP"):
- print ' INFO INDISPONIBLE'
- return []
- else:
- output.append(' Vers %-30.30s: %-18.18s' % (data.pop(0), data.pop(0)))
- return output
- def main():
- parser = OptionParser()
- parser.usage = '%prog -l <lineid> station name'
- parser.add_option("-l", "--lineid", dest="lineid",
- action="append", default=[],
- help="pour Metro Mxx pour Bus Bxxx")
- parser.add_option("-v", "--verbose", dest="verbose",
- action="count", default=0)
- options, args = parser.parse_args()
- log.basicConfig(stream=sys.stdout, level=options.verbose and log.DEBUG or log.INFO,
- format='%(asctime)s %(message)s',
- datefmt='%H:%M:%S',
- )
- os.system('title Horaires RATP')
- if not options.verbose:
- os.system('mode 64,14')
- if not args:
- print('Horaires RATP pour MetronomeBus v0.5\n')
- ligne=int(raw_input('Num. de ligne : '))
- reseau='B'
- arrsta='l\'arret'
- if ligne < 15:
- reseau='M'
- arrsta='la station'
- options.lineid=[reseau+str(ligne)]
- station=raw_input('Nom de '+arrsta+': ')
- args = [station]
- s = Service()
- while True:
- if not options.verbose:
- os.system('cls')
- try:
- for lid in options.lineid:
- kwargs = dict(lineid=lid.upper(), station=' '.join(args), time=datetime.now().strftime('%H:%M:%S'))
- header = 'A %(time)s - Ligne: %(lineid)s - Station: %(station)s' %kwargs
- print header.center(60)
- print '='*60
- if lid.upper().startswith('M'):
- direct='AR'
- else:
- direct='A'
- for directionsens in direct:
- output = s.get(directionsens=directionsens, **kwargs)
- if output:
- print '\n'.join(output)
- print '- - -'.center(60)
- else:
- print '-* Pas de donnees *-'.center(60)
- print '\r'
- raw_input('APPUYER SUR UNE TOUCHE POUR QUITTER')
- return
- print 'CTRL-C pour Quitter'
- time.sleep(20)
- except KeyboardInterrupt:
- print '\r'
- return
- except Exception, e:
- log.error('Error: %r', e)
- s = Service()
- if __name__ == '__main__':
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement