Un petit script pour réaliser des stats d'utilisation de stations de vélib.

velib_stats.py 2.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #! /usr/bin/env python3.3
  2. import sys
  3. import os
  4. import datetime
  5. import urllib3
  6. import xml.etree.ElementTree as ET
  7. # Change working directory if necessary
  8. file_path = os.path.dirname(__file__)
  9. if file_path != "":
  10. os.chdir(file_path)
  11. if len(sys.argv) != 2:
  12. exit('Usage : velib_stats.py Station_number')
  13. # Parameters
  14. station_number = int(sys.argv[1])
  15. url = ('http://www.velib.paris.fr/service/stationdetails/paris/' +
  16. str(station_number))
  17. # Initialize libraries
  18. http = urllib3.PoolManager()
  19. today = datetime.datetime.now()
  20. # Get the response from velib REST API
  21. r = http.request('GET', url)
  22. if r.status == 200:
  23. station_xml = ET.fromstring(r.data)
  24. # Get station status
  25. write = today.strftime('%H\t\t%M')
  26. for child in station_xml.iter('available'):
  27. write += "\t\t"+child.text
  28. for child in station_xml.iter('free'):
  29. write += "\t\t"+child.text
  30. try:
  31. # If file exists, check last updated day
  32. with open('data/'+str(station_number), 'r') as fh:
  33. lines = fh.readlines()
  34. for line in reversed(lines):
  35. if "Jour" in line:
  36. previous_day = line[7:]
  37. # If today != last day of update, add a header
  38. previous_day = previous_day.split("/")
  39. if (previous_day[0] != today.strftime('%d') and
  40. previous_day[1] != today.strftime('%m')):
  41. write = ("Jour = "+today.strftime('%d/%m')+"\n" +
  42. "======================\n" +
  43. "Heure\t\tMin\t\tDispos\t\tPlaces\n" +
  44. write)
  45. # Write content to file
  46. with open('data/'+str(station_number), 'a') as fh:
  47. fh.write("\n"+write)
  48. print(write)
  49. except IOError:
  50. # If file doesn't exist, create it
  51. write = ("Données pour la station n°"+str(station_number)+"\n" +
  52. "==============================================\n\n" +
  53. "Jour = "+today.strftime('%d/%m')+"\n" +
  54. "======================\n" +
  55. "Heure\t\tMin\t\tDispos\t\tPlaces\n" +
  56. write)
  57. with open('data/'+str(station_number), 'w') as fh:
  58. fh.write(write)
  59. print(write)
  60. else:
  61. exit('Erreur lors de la récupération des infos sur la station' +
  62. station_number)