Tag Archives: python

Un petit script python qui m’envoie des mails quand le RER est malade

Un petit script tout moche python qui m’envoie des mails quand le RER est malade, lancé avec une crontab aux horaires qui m’intéressent, et voilà!

#!/usr/bin/python
# -*- coding: utf-8 -*-

import time
now = time.ctime()


# RATP API part
## c'est la partie magique, merci Pierre!
import requests
r = requests.get("http://api-ratp.pierre-grimaud.fr/data/trafic/rer")
data = r.text
print(data)

import json
parsed_json = json.loads(data)
if parsed_json["trafic"] == "perturbation":
  print(parsed_json["perturbations"])
  mailbody = parsed_json["perturbations"]

  ## mail part
  import subprocess
  import smtplib
  import email.utils
  from email.mime.text import MIMEText

  recipients = "qqn@mail.com,joe@example.net"
  # Create the message
  msg = MIMEText(str(mailbody))
  msg['To'] = recipients
  msg['From'] = "noreply-rapt@whateversnmpworkshere.fr"
  msg['Subject'] = "RERB status -- " + now

  server = smtplib.SMTP('smtp.example.net')
  log = server.set_debuglevel(True) # show communication with the server
  try:
      server.sendmail(msg["From"], msg["To"].split(","), msg.as_string())
  finally:
      server.quit()
  #print(log)

automating #Twitter with #raspberrypi

I’ve been tweeting pictures and re-tweeting twits automatically for a few years now using two python tools.

  1. Twython
  2. on github
    Here’s an example script for Twython

  3. TwitterFollowBot
  4. on github
    Here’s an example script for TwitterFollowBot

Both require to have an already created Twitter app (https://apps.twitter.com/) and a little bit of python.

Temperature and humidity graph with raspberry pi

Top posted update:
Now it looks like this
pre-requisites:

  • a pinch of pygal
  • 1 raspberry pi (I used model B)
  • breadboard + accessories
  • DHT22 (or equivalent)

I just followed Adafruit’s tutorial for the wiring and the software
Then I did a slight modification to the script provided by Adafruit to write the data to a log file (temp-hum.log) instead of google drive spreadsheet.

Actual work
Updated code on Github
To generate the log file that will be parsed by pygal on github
Adafruit’s code for the sensor forked on github

A short python script to generate the graphic using Pygal:

#!/usr/bin/env python

import pygal

temp = []
hum  = []

logdata = open('temp-hum.log','r')
for line in logdata.readlines():
  line = line.split()[1:]
  temp.append(float(line[0]))
  hum.append(float(line[1]))

print(temp)
print(hum)

line_chart = pygal.Line(width=1200)
line_chart.title = 'Temperature Humidity'
line_chart.add('Temperature *C', temp)
line_chart.add('Humidity %', hum) 
line_chart.render_to_file('temp-hum.svg')
breadboard and flat cable
breadboard and flat cable
DHT22 and cables
DHT22 and cables
r-pi and all
r-pi and all
Adafruit_DHT
Adafruit_DHT
DHT22 sensor
DHT22 sensor
breadboard
breadboard
r-pi with sensor
r-pi with sensor

And the graphic looks like:
this

Sources: Adafruit DHT22 tutorial

argparse example in python

argparse_example.py

import sys
#we need argparse
try:
    import argparse
except ImportError:
    print "Please install the argparse python module\non Debian systems you can use:\napt-get install python-argparse"
    sys.exit()

parser = argparse.ArgumentParser(
    prog = 'argparse_example.py',                                                           # the name of the program
    description = "This is a tool to compare files. It compares the md5 of each file.",     # text displayed on top of --help
    epilog = 'just an example of the beauty of the code.')                                  # last text displayed 

#parser.add_argument('','',"",default=)
parser.add_argument('-V', '--version', action='version', version='%(prog)s 0.1')
parser.add_argument('-1','--path1',action="store",dest='path1',help='path for first file')
parser.add_argument('-2','--path2',action="store",dest='path2',help='path for second file')
parser.add_argument('-w','--warm', action="store_true",dest='planet',help='use to fix global warming if needed',default=False)
arguments = parser.parse_args()

path1 = arguments.path1  # look at dest  in the parser.add_argument lines
path2 = arguments.path2
planet = arguments.planet
if path1 and path2 != None:
    print(path1)
    print(path2)

if planet == True:
  print("Global warming issue fixed, you can start polluting again")

python-virtenv + django


tatico@asgard:~$ mkdir virtenv
tatico@asgard:~$ virtualenv --no-site-packages -p /usr/bin/python2.6 ~/virtenv/
Running virtualenv with interpreter /usr/bin/python2.6
New python executable in /home/tatico/virtenv/bin/python2.6
Also creating executable in /home/tatico/virtenv/bin/python
Installing distribute..................................................................................................................................................................................done.
tatico@asgard:~$ cd virtenv/
tatico@asgard:~/virtenv$ ls
bin include lib
tatico@asgard:~/virtenv$ cd bin/
tatico@asgard:~/virtenv/bin$ ls
activate activate_this.py easy_install easy_install-2.6 pip python python2.6
tatico@asgard:~/virtenv/bin$ cd ..
tatico@asgard:~/virtenv$ source bin/activate
(virtenv)tatico@asgard:~/virtenv$
(virtenv)tatico@asgard:~/virtenv$ python --version
Python 2.6.5+
(virtenv)tatico@asgard:~/virtenv$ python
Python 2.6.5+ (release26-maint, Jul 30 2010, 23:04:10)
[GCC 4.4.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
(virtenv)tatico@asgard:~/virtenv$ pip install django
Downloading/unpacking django
Downloading Django-1.2.3.tar.gz (6.3Mb): 6.3Mb downloaded
Running setup.py egg_info for package django
warning: no files found matching 'django/dispatch/LICENSE.txt'
warning: no files found matching '*' under directory 'examples'
Installing collected packages: django
Running setup.py install for django
changing mode of build/scripts-2.6/django-admin.py from 644 to 755
warning: no files found matching 'django/dispatch/LICENSE.txt'
warning: no files found matching '*' under directory 'examples'
changing mode of /home/tatico/virtenv/bin/django-admin.py to 755
Successfully installed django
Cleaning up...
(virtenv)tatico@asgard:~/virtenv$ deactivate
tatico@asgard:~/virtenv$ ls
bin include lib
tatico@asgard:~/virtenv$ source bin/activate
(virtenv)tatico@asgard:~/virtenv$ django-admin.py
Usage: django-admin.py subcommand [options] [args]

Options:
-v VERBOSITY, --verbosity=VERBOSITY
Verbosity level; 0=minimal output, 1=normal output,
2=all output
--settings=SETTINGS The Python path to a settings module, e.g.
"myproject.settings.main". If this isn't provided, the
DJANGO_SETTINGS_MODULE environment variable will be
used.
--pythonpath=PYTHONPATH
A directory to add to the Python path, e.g.
"/home/djangoprojects/myproject".
--traceback Print traceback on exception
--version show program's version number and exit
-h, --help show this help message and exit

Type 'django-admin.py help ' for help on a specific subcommand.

Available subcommands:
cleanup
compilemessages
createcachetable
dbshell
diffsettings
dumpdata
flush
inspectdb
loaddata
makemessages
reset
runfcgi
runserver
shell
sql
sqlall
sqlclear
sqlcustom
sqlflush
sqlindexes
sqlinitialdata
sqlreset
sqlsequencereset
startapp
startproject
syncdb
test
testserver
validate
(virtenv)tatico@asgard:~/virtenv$ deactivate
tatico@asgard:~/virtenv$ django-admin.py
tatico@asgard:~/virtenv$ source bin/activate
(virtenv)tatico@asgard:~/virtenv$ django-admin.py testserver
Error: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.
(virtenv)tatico@asgard:~/virtenv$ deactivate