Advertisement
Guest User

Horaires RATP

a guest
Apr 16th, 2012
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.46 KB | None | 0 0
  1. #Horaires RATP for MetronomeBus v0.5
  2. #Copyright <copyright>
  3. #
  4. #Permission is hereby granted, free of charge, to any person obtaining a copy of
  5. #this software and associated documentation files (the "Software"), to deal in
  6. #the Software without restriction, including without limitation the rights to
  7. #use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
  8. #of the Software, and to permit persons to whom the Software is furnished to do
  9. #so, subject to the following conditions:
  10. #The above copyright notice and this permission notice shall be included in all
  11. #copies or substantial portions of the Software.
  12. #
  13. #The Software is provided "as is", without warranty of any kind, express or
  14. #implied, including but not limited to the warranties of merchantability,
  15. #fitness for a particular purpose and noninfringement. In no event shall the
  16. #authors or copyright holders be liable for any claim, damages or other
  17. #liability, whether in an action of contract, tort or otherwise, arising from,
  18. #out of or in connection with the software or the use or other dealings in the
  19. #Software.
  20. #
  21. # </copyright>
  22. # <author>Antoine FERRON</author>
  23. # <date>2012-16-04</date>
  24. # <summary>Affiche les horaires aux arrets de la RATP</summary>
  25. # Based On: Script RATP by Gawel (Gael Pasgrimaud) : hg.gawel.org/ratp/
  26. #
  27. # usage : [ -l <lineid> station name ]
  28. #
  29. # Compiled with : Python 2.7.3, PyWin32 2.1.7, PyInstaller 1.5.1
  30.  
  31. # -*- coding: utf-8 -*-
  32. import re
  33. import os
  34. import sys
  35. import time
  36. import urllib2
  37. import httplib
  38. import logging as log
  39. from datetime import datetime
  40. from optparse import OptionParser
  41.  
  42. def debug(func):
  43.     def wrapper(*args, **kwargs):
  44.         result = func(*args, **kwargs)
  45.         log.debug('%s(*%r, **%r) -> %s', func.func_name, args[1:], kwargs, result)
  46.         return result
  47.     return wrapper
  48.  
  49. entities = (
  50.         ('</', ''),
  51.         ('&eacute;', 'e'),
  52.         ('&egrave;', 'e'),
  53.         ('&acirc;', 'a'),
  54.         ('&ocirc;', 'o'),
  55.         )
  56.  
  57. def clean_html(data):
  58.     if data.startswith('<b>'):
  59.         data = data.replace('<b>', '').replace('</b>', '')
  60.     for a, b in entities:
  61.         data = data.replace(a, b)
  62.     return data
  63.  
  64. class Service(object):
  65.  
  66.     def __init__(self):
  67.         self.headers = {
  68.                 'User-Agent': 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; fr; rv:1.9.2) Gecko/20100115 Firefox/3.6',
  69.                 }
  70.         self.conn = httplib.HTTPConnection("wap.ratp.fr")
  71.  
  72.     def open(self, path, **kwargs):
  73.         self.conn.request("GET", path , '', self.headers)
  74.         resp = self.conn.getresponse()
  75.         return resp
  76.  
  77.     @debug
  78.     def post(self, path='', **kwargs):
  79.         resp = self.open(path)
  80.         self.headers['referer'] = 'http://www.ratp.fr%s' % path
  81.         data = resp.read()
  82.         if 'body' in data:
  83.             data = data.split('<body>')[1]
  84.             data = data.replace('div', '\n')
  85.             data = data.replace('\n          &gt;&nbsp;', '<b>')
  86.             data = re.findall('.*class="(?:bg|schmsg)(?:[0-9]+)">(.*)', data)
  87.             data = [clean_html(d) for d in data if d[:3] in ('<b>')]
  88.         return data
  89.  
  90.     def close(self):
  91.         self.conn.close()
  92.  
  93.     def get(self,**kwargs):
  94.         kwargs['reseau'] = kwargs.get('lineid')[0] == 'M' and 'metro' or 'bus'
  95.         kwargs['stationname'] = kwargs['station'].replace(' ', '+')
  96.         url = '/siv/schedule?service=next'
  97.         url += '&reseau=%(reseau)s&referer=station&lineid=%(lineid)s' % kwargs
  98.         url += '&directionsens=%(directionsens)s' % kwargs
  99.         url += '&stationname=%(stationname)s&submitAction=Valider' % kwargs
  100.         data = self.post(url)
  101.         output = []
  102.         while data:
  103.             if len(data) == 1:
  104.                 output.append('        '+data.pop())
  105.             if len(data) > 1:
  106.                 if data[0].startswith("INFO INDISP"):
  107.                     print '        INFO INDISPONIBLE'
  108.                     return []
  109.                 else:
  110.                     output.append('        Vers %-30.30s: %-18.18s' % (data.pop(0), data.pop(0)))
  111.         return output
  112.  
  113. def main():
  114.     parser = OptionParser()
  115.     parser.usage = '%prog -l <lineid> station name'
  116.     parser.add_option("-l", "--lineid", dest="lineid",
  117.                       action="append", default=[],
  118.                       help="pour Metro Mxx pour Bus Bxxx")
  119.     parser.add_option("-v", "--verbose", dest="verbose",
  120.                       action="count", default=0)
  121.     options, args = parser.parse_args()
  122.  
  123.     log.basicConfig(stream=sys.stdout, level=options.verbose and log.DEBUG or log.INFO,
  124.                     format='%(asctime)s %(message)s',
  125.                     datefmt='%H:%M:%S',
  126.                     )
  127.     os.system('title Horaires RATP')
  128.     if not options.verbose:
  129.         os.system('mode 64,14')
  130.     if not args:
  131.         print('Horaires RATP pour MetronomeBus v0.5\n')
  132.         ligne=int(raw_input('Num. de ligne : '))
  133.         reseau='B'
  134.         arrsta='l\'arret'
  135.         if ligne < 15:
  136.             reseau='M'
  137.             arrsta='la station'
  138.         options.lineid=[reseau+str(ligne)]
  139.         station=raw_input('Nom de '+arrsta+': ')
  140.         args = [station]
  141.     s = Service()
  142.     while True:
  143.         if not options.verbose:
  144.             os.system('cls')
  145.         try:
  146.             for lid in options.lineid:
  147.                 kwargs = dict(lineid=lid.upper(), station=' '.join(args), time=datetime.now().strftime('%H:%M:%S'))
  148.                 header = 'A %(time)s - Ligne: %(lineid)s - Station: %(station)s' %kwargs
  149.                 print header.center(60)
  150.                 print '='*60
  151.                 if lid.upper().startswith('M'):
  152.                     direct='AR'
  153.                 else:
  154.                     direct='A'
  155.                 for directionsens in direct:
  156.                     output = s.get(directionsens=directionsens, **kwargs)
  157.                     if output:
  158.                         print '\n'.join(output)
  159.                         print '- - -'.center(60)
  160.                     else:
  161.                         print '-* Pas de donnees *-'.center(60)
  162.                         print '\r'
  163.                         raw_input('APPUYER SUR UNE TOUCHE POUR QUITTER')
  164.                         return
  165.             print 'CTRL-C pour Quitter'
  166.             time.sleep(20)  
  167.         except KeyboardInterrupt:
  168.             print '\r'
  169.             return
  170.         except Exception, e:
  171.             log.error('Error: %r', e)
  172.             s = Service()
  173.        
  174. if __name__ == '__main__':
  175.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement