# -*- coding: utf-8 -*-
#Horaires RATP StandAlone v0.96
#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-06-06</date>
# <summary>Affiche les horaires aux arrets de la RATP</summary>
# Based On: Script RATP by Gawel (Gael Pasgrimaud) : hg.gawel.org/ratp/
# This is the standalone version, which not requires a Metronomebus conected on a USB port.
#
# usage : [ -l <lineid> station name -d {1|2}} ]
#
# Compiled with : Python 2.7.3, PyWin32 2.1.7, PyInstaller 1.5.1
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('class="subtitle">Direction <b class="bwhite">', 'class="bg3"><b> Direction ')
data = data.replace('\n > ', '<b>')
data = re.findall('.*class="(?:bg|schmsg|space)(?:[0-9]+)">(.*)', data)
data = [clean_html(d) for d in data if d[:3] in ('<b>')]
self.conn.close()
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)
return data
def dispinfo(lid,args,direction):
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
s=Service()
diraff=0
if lid.upper().startswith('M'):
direct='AR'
direct=direct[direction-1]
direction=1
else:
direct='A'
for directionsens in direct:
outputd = s.get(directionsens=directionsens, **kwargs)
if outputd:
data=outputd
output = []
ligne=0
datatemp=''
while data:
if len(data) == 1:
datai=data.pop(0)
if diraff==direction:
if datai.startswith("DERNIE"):
output.append(40*' '+datai)
elif datai.startswith("SERVIC"):
output.append(' '+datai)
else:
output.append(8*' '+datai)
if len(data) > 1:
datatemp=data[0]
if datatemp.startswith(" Direction"):
ligne=0
diraff=diraff+1
stroutput = '%.30s ' % data.pop(0)
stroutput = stroutput.center(50,'-').center(60)
if diraff==direction:
output.append('\n'+stroutput)
elif datatemp.startswith("DERNIE"):
datai=data.pop(0)
if diraff==direction:
output.append(40*' '+datai)
else:
i1=data.pop(0)
i2=data.pop(0)
if diraff==direction:
if i1.startswith("INFO INDISP"):
print ' INFO INDISPONIBLE'
return []
elif i1.startswith("SERVIC"):
output.append(' '+i1+' '+i2)
else:
ligne=ligne+1
output.append(' Vers %-30.30s: %-16.16s' % (i1, i2))
print '\n'.join(output)
else:
print '-* Pas de donnees / Arret inconnu *-'.center(60)
print '\r'
raw_input('APPUYER SUR UNE TOUCHE POUR QUITTER')
return 1
print '\nCTRL-C pour Quitter'
return 0
def dispdirect(lid,args):
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
s=Service()
direction=0
if lid.upper().startswith('M'):
direct='AR'
else:
direct='A'
for directionsens in direct:
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=%s' % directionsens
url += '&stationname=%(stationname)s&submitAction=Valider' % kwargs
path=url
try:
resp = s.open(path)
s.headers['referer'] = 'http://www.ratp.fr%s' % path
data = resp.read()
except Exception, (errnum, errmsg) :
if errnum==10054:
print '! Erreur de connexion a Internet'
elif errnum==11001:
print '! Erreur de connexion reseau\n'
elif errnum==11003:
print '! Erreur de connexion reseau\n'
elif errnum==11004:
print '! Erreur de connexion reseau\n'
else:
log.error('! Erreur numero: %r : %r \n', errnum, errmsg)
raw_input ('\nAPPUYER SUR UNE TOUCHE POUR QUITTER')
return 1
if 'body' in data:
data = data.split('<body>')[1]
data = data.replace('div', '\n')
data = data.replace('class="subtitle">Direction <b class="bwhite">', 'class="bg3"><b> Direction ')
data = data.replace('\n > ', '<c>')
data = re.findall('.*class="(?:bg|schmsg|space)(?:[0-9]+)">(.*)', data)
data = [clean_html(d) for d in data if d[:3] in ('<b>')]
s.conn.close()
if data:
output = []
ligne=0
while data:
if len(data) == 1:
if data[0].startswith("DERNIE"):
output.append(40*' '+data.pop())
else:
output.append(8*' '+data.pop())
if len(data) > 1:
if data[0].startswith(" Direction"):
stroutput = '%.50s ' % data.pop(0)
direction = direction + 1
print('\n '+str(direction)+' ) '+stroutput)
else:
data.pop(0)
else:
print '-* Pas de donnees / Arret inconnu *-'.center(60)
print '\r'
raw_input('APPUYER SUR UNE TOUCHE POUR QUITTER')
return 1
return 0
def main():
parser = OptionParser()
parser.usage = '%prog -l <lineid> station name -d <direction>'
parser.add_option("-l", "--lineid", dest="lineid",
action="append", default=[],
help="pour Metro Mxx pour Bus Bxxx")
parser.add_option("-d", "--direction", dest="direction",
action="append", default=["0"])
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,12')
if not args:
print 'Horaires RATP StandAlone v0.96\n'
try:
ligne=int(raw_input('Num. de ligne : '))
except ValueError:
print '\nMerci d\'entrer un nombre :\nEntre 1 et 14 pour le metro\nEntre 20 et 999 pour le bus\n'
raw_input ('APPUYER SUR UNE TOUCHE POUR QUITTER')
return
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]
if not options.verbose:
os.system('cls')
retu = dispdirect(options.lineid[0], args)
if retu>0:
return
choixdir=raw_input('\nDirection (1 ou 2): ')
options.direction=['0',choixdir]
while True:
if not options.verbose:
os.system('cls')
if options.direction[1].__len__()>1:
print '\nMerci d\'entrer 1 ou 2 pour indiquer la direction\n'
raw_input('APPUYER SUR UNE TOUCHE POUR QUITTER')
return
if ord(options.direction[1])-48>2:
print '\nMerci d\'entrer 1 ou 2 pour indiquer la direction\n'
raw_input('APPUYER SUR UNE TOUCHE POUR QUITTER')
return
try:
for lid in options.lineid:
retu = dispinfo(lid,args,ord(options.direction[1])-48)
if retu>0:
return
time.sleep(12)
except KeyboardInterrupt:
print '\r'
return
except Exception, (errnum, errmsg) :
if errnum==10054:
print '! Erreur de connexion a Internet'
elif errnum==11001:
print '! Erreur de connexion reseau\n'
elif errnum==11003:
print '! Erreur de connexion reseau\n'
elif errnum==11004:
print '! Erreur de connexion reseau\n'
else:
log.error('! Erreur numero: %r : %r \n', errnum, errmsg)
raw_input ('\nAPPUYER SUR UNE TOUCHE POUR QUITTER')
return
if __name__ == '__main__':
main()