Skip to content

Instantly share code, notes, and snippets.

@andersonvom
Last active April 11, 2016 02:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andersonvom/ebc231861fc0293e4468 to your computer and use it in GitHub Desktop.
Save andersonvom/ebc231861fc0293e4468 to your computer and use it in GitHub Desktop.
Acompanhe os resultados das eleições para presidente de 2014 sem sair do terminal!
import logging
import os
import re
import requests
import subprocess
import time
loggers = {}
def log_change(filename, votes):
last_line = subprocess.check_output(['tail', '-n1', filename])
elements = [-1, -1]
if last_line:
elements = re.split('\t', last_line)
last_votes = int(elements[1])
if votes != last_votes:
loggers[filename].info(votes)
def log(candidate, votes):
def setup_logging(filename):
if filename not in loggers:
handler = logging.FileHandler(filename)
handler.setFormatter(logging.Formatter('%(asctime)s\t%(message)s'))
candidate_logger = logging.getLogger(filename)
candidate_logger.addHandler(handler)
candidate_logger.setLevel(logging.INFO)
loggers[filename] = candidate_logger
filename = '%s.log' % candidate.lower()
setup_logging(filename)
log_change(filename, votes)
def sort_results(candidates, blank, null):
results = [
{'name': candidate['nm'], 'votes': int(candidate['v'])}
for candidate in candidates
]
sorted_results = sorted(
results,
key=lambda candidate: (-int(candidate['votes']), candidate['name'])
)
if sorted_results:
sorted_results.append({'name': 'Brancos', 'votes': blank})
sorted_results.append({'name': 'Nulos', 'votes': null})
return sorted_results
def display_results(candidates, blank, null):
sorted_candidates = sort_results(candidates, blank, null)
for candidate in sorted_candidates:
name = candidate['name']
votes = candidate['votes']
log(name, votes)
print('%-20s\t%10s' % (candidate['name'], candidate['votes']))
def get_results(url):
results = {}
try:
response = requests.get(url)
response.raise_for_status()
results = response.json()
except requests.exceptions.RequestException as exc:
print('Error retrieving results data: %s' % exc)
return results
def main():
while True:
URL = ('http://divulga.tse.jus.br/2014/divulgacao/oficial/143'
'/dadosdivweb/br/br-0001-e001431-w.js?1412533471853')
results = get_results(URL)
candidates = results.get('cand') or []
blank = int(results.get('vb') or 0)
null = int(results.get('vn') or 0)
os.system('clear')
display_results(candidates, blank, null)
time.sleep(10)
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment