Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] Complete rewrite #11

Open
wants to merge 3 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 17 additions & 15 deletions findstation.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#!/usr/bin/python
#!/usr/bin/env python
# coding=utf-8
from __future__ import print_function

"""Pendla FindStation v1.3.0 - Hjälper dig hitta stationen att hinna hem ifrån!

Expand All @@ -17,6 +18,7 @@
try:
# For Python 3.0 and later
from urllib.request import urlopen
from urllib.parse import quote
except ImportError:
# Fall back to Python 2's urllib2
from urllib2 import urlopen, quote
Expand All @@ -41,38 +43,38 @@ class color:


def get_search_string():
string = raw_input("Sök efter hållplats: ")
print
string = input("Sök efter hållplats: ")
print()
return string


def print_search_results(results, choice=False):
"""Print a pretty header before outputing search results"""
if choice:
print color.GREEN + color.BOLD + '%9s' % "ID ",
print(color.GREEN + color.BOLD + '%9s' % "ID ", end=' ')
else:
print color.GREEN + color.BOLD + '%-4s' % "ID ",
print "Namn" + color.END
print(color.GREEN + color.BOLD + '%-4s' % "ID ", end=' ')
print("Namn" + color.END)

choices = {}

i = 1
for r in results:
choices[i] = {r['SiteId']: r['Name']}
if choice:
print '%-4s' % ("#" + str(i)),
print('%-4s' % ("#" + str(i)), end=' ')
i += 1
print color.DARKCYAN + r['SiteId'] + color.YELLOW + " " + r['Name'],
print color.END
print(color.DARKCYAN + r['SiteId'] + color.YELLOW + " " + r['Name'], end=' ')
print(color.END)

if choice:
print
choice = raw_input("Välj hållplats: ")
print()
choice = input("Välj hållplats: ")
if int(choice) in choices:
return choices[int(choice)]
else:
os.system('clear')
print "Var vänlig ange ett giltigt nummer.\n"
print("Var vänlig ange ett giltigt nummer.\n")
return print_search_results(results, True)
return False

Expand All @@ -98,9 +100,9 @@ def main(arguments=None, search_string=None):
data = json.load(stream)

if data['StatusCode'] != 0:
print "StatusCode: %s\nMessage: %s" % (
print("StatusCode: %s\nMessage: %s" % (
data['StatusCode'], data['Message']
)
))
else:
choice = print_search_results(data['ResponseData'], choice)

Expand All @@ -112,5 +114,5 @@ def main(arguments=None, search_string=None):
try:
main(arguments)
except KeyboardInterrupt:
print "\nExiting..."
print("\nExiting...")
exit()
59 changes: 30 additions & 29 deletions pendla.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#!/usr/bin/python
#!/usr/bin/env python
# coding=utf-8

"""Pendla v1.3.0 - Hjälper dig hinna hem!
Expand All @@ -21,7 +21,8 @@
from urllib.request import urlopen
except ImportError:
# Fall back to Python 2's urllib2
from urllib2 import urlopen, URLError, HTTPError
from urllib.request import urlopen
from urllib.error import URLError, HTTPError
import json
import os
from datetime import datetime
Expand All @@ -31,7 +32,7 @@
try:
import yaml
except ImportError:
print "Requires PyYAML module to function"
print("Requires PyYAML module to function")
exit()


Expand Down Expand Up @@ -60,8 +61,8 @@ def get_string_time(self, unix):
return datetime.strftime(datetime.strptime(unix, "%Y-%m-%dT%H:%M:%S"), "%H:%M")

def print_site(self):
print
print color.DARKCYAN + color.BOLD + self.site_name + color.END
print()
print(color.DARKCYAN + color.BOLD + self.site_name + color.END)

def print_departures(self):
i = 0
Expand Down Expand Up @@ -97,19 +98,19 @@ def print_departures(self):
if (tt_unix - now) < self.distance * 60:
continue

print color.END + remaining_time(self.distance, ex_unix),
print color.YELLOW + '%-7s' % d['DisplayTime'] + color.END,
print(color.END + remaining_time(self.distance, ex_unix), end=' ')
print(color.YELLOW + '%-7s' % d['DisplayTime'] + color.END, end=' ')
if tt_unix == ex_unix:
print '%-11s' % tt_string,
print('%-11s' % tt_string, end=' ')
else:
print '%-11s' % (tt_string+"/"+color.RED+ex_string+color.END),
print '%-11s' % (color.DARKCYAN + d['LineNumber'] + " " + color.YELLOW + d['Destination']) + color.END
print('%-11s' % (tt_string+"/"+color.RED+ex_string+color.END), end=' ')
print('%-11s' % (color.DARKCYAN + d['LineNumber'] + " " + color.YELLOW + d['Destination']) + color.END)
if d['Deviations']:
print color.DARKCYAN + "- " + d['Deviations'][0]['Text'][:80] + color.END
print(color.DARKCYAN + "- " + d['Deviations'][0]['Text'][:80] + color.END)

i += 1
if u == 0:
print "Inga avgångar matchade din sökning."
print("Inga avgångar matchade din sökning.")

def __init__(self, quick=False):
self.traffic_types = ["Metros", "Buses", "Trains", "Trams", "Ships"]
Expand Down Expand Up @@ -149,20 +150,20 @@ def get_api_json_data(site_id):
try:
raise APIError(data['StatusCode'], data['Message'])
except APIError as e:
print "StatusCode: %s\nMessage: %s" % (
print("StatusCode: %s\nMessage: %s" % (
e.code, e.message
)
))
return data


def print_header(quick=False):
"""Print a pretty header before outputing stations and departures"""
if not quick:
print color.GREEN + color.BOLD + '%-8s' % "Gå om",
print color.GREEN + color.BOLD + '%-8s' % "Avgång",
print '%-11s' % "Tid",
print "Destination",
print color.END
print(color.GREEN + color.BOLD + '%-8s' % "Gå om", end=' ')
print(color.GREEN + color.BOLD + '%-8s' % "Avgång", end=' ')
print('%-11s' % "Tid", end=' ')
print("Destination", end=' ')
print(color.END)


def remaining_time(distance, departure):
Expand Down Expand Up @@ -190,7 +191,7 @@ def read_config(config_file):
config_data = yaml.load(stream)
return config_data
except IOError:
print "No configuration file found!"
print("No configuration file found!")
raise


Expand All @@ -211,13 +212,13 @@ def main(args):
import findstation
os.system('clear')
result = findstation.main(None, qstation)
for k, v in result.iteritems():
for k, v in result.items():
stations[k] = Station(True)
stations[k].site_name = v
stations[k].lines = qslines
break
else:
for k, v in read_config(CONFIG_FILE).iteritems():
for k, v in read_config(CONFIG_FILE).items():
stations[k] = Station()
stations[k].site_name = v['site_name']
stations[k].distance = v['distance']
Expand All @@ -229,18 +230,18 @@ def main(args):
# Loop through all stations and:
# (1) fetch data from API
# (2) print relevant departures
for s, o in stations.iteritems():
for s, o in stations.items():
o.print_site()
try:
o.api_data = get_api_json_data(s)
except HTTPError, e:
print "HTTP error: " + str(e.code)
except HTTPError as e:
print("HTTP error: " + str(e.code))
except URLError:
print "Network error"
print("Network error")
except APIError as e:
print "StatusCode: %s\nMessage: %s" % (
print("StatusCode: %s\nMessage: %s" % (
e.code, e.message
)
))
else:
o.print_departures()
if loop:
Expand All @@ -254,4 +255,4 @@ def main(args):
main(arguments)
exit()
except KeyboardInterrupt:
print " Exiting..."
print(" Exiting...")
9 changes: 9 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,11 @@ Pendla v1.3.0

En liten applikation som visar kommande avgångar du faktiskt hinner till!

## Installation

Kör 'pip install -r requirements.txt' för att installera de extra moduler
som krävs för att köra applikationen.

## Instruktioner

Kör './findstation.py' för att hitta din station, och kopiera ID-numret.
Expand All @@ -19,6 +24,10 @@ Du kan även söka stationers ID-nummer snabbt genom att köra:

## Versioner

#### 1.3.1
- Kör python från 'env' istället för /usr/bin/python specifikt.
- Lägger till instruktioner för att installera stödmoduler

### 1.3.0

- Gör det möjligt att loopa även vid snabbsökningar
Expand Down
3 changes: 3 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
PyYAML
doctop
pprintpp