Voila la dernière version de mon script python :cool:
Fonctionnalité
- il récupère la météo sur weather.com
- il génère le fichier xml dans le dossier ou se trouve le script (possibilité de rajouter une option pour ça ?)
- il crée la ligne cron correspondant
- Très facile à utiliser
Dans un terminal taper ça
python background.py -i /home/tyrus/background/ -v FRXX0115 -a
Cette commande rajoute la ligne cron avec le package des image dans le dossier
/home/tyrus/background/ et avec la référence de la ville correspondant à FRXX0115
Pour supprimer le cron vous faite simplement
python background.py -e
Et pour plus d'info
python background.py -h
Bon wallpaper dynamique
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import sys, urllib, getopt,os, commands,re
from xml.dom.minidom import Document
from xml.dom import minidom
def usage():
print "Logiciel pour mettre en place un fond écran en fonction de la météo et de l\'heure \n ------Commande Possible ------- \n -h,--help pour obtenir cet aide \n -v,-ville pour définir la variable correspondant à votre ville grace au site weather.com \n -i,--images pour définir le dossier ou se trouve le pack d\'image \n -a,--ajouter pour rajouter dans le cron \n -e,--enlever pour supprimer dans le cron "
def supprimerligner(texte,chaine):
texte = "\n".join([em for em in texte.split('\n') if re.search(chaine,em) == None ])
return texte
def ajouttext(chemin,texte):
f = file(chemin,'w')
f.write(texte)
f.close()
#Variable
path =''
ville =''
cron = 3
filename = sys.argv[0]
fileprog = sys.path[0]
# Création des commande de background.py
try:
opts, args = getopt.getopt(sys.argv[1:], "haev:i:", ["help","ajouter","enlever","ville=","images="])
except getopt.error,err:
usage()
print err
sys.exit(2)
for opt, arg in opts:
if opt in ("-h","--help"):
usage()
sys.exit(2)
elif opt in ("-a","--ajouter"):
cron = 1
elif opt in ("-e","--enlever"):
cron = 2
elif opt in ("-v","--ville"):
ville = arg
elif opt in ("-i","--images") :
path = arg
if ((ville == '') | (path == '') | len(ville) != 8) & (cron != 2) :
usage()
sys.exit(2)
#Enregistrement ou suppression dans le cron
if cron == 3:#laisser en l'état
pass
elif cron == 1:#enregistrement dans le crontab
crontab = commands.getoutput("crontab -l")
crontab = supprimerligner(crontab,filename)
fichier = [ em for em in sys.argv[1:] if (em in ( '-a','--ajouter','-e','--enlever','-h','--help')) == False ]
crontab = crontab + "\n*/15 * * * * "+ sys.executable +" "+ os.path.join(fileprog,sys.argv[0]) +" "+ " ".join(fichier) +"\n"
print "Rajouter la ligne suivante dans votre crontab \n*/15 * * * * "+ sys.executable +" "+ os.path.join(fileprog,sys.argv[0]) +" " + " ".join(fichier) +" ?\n Taper Yes ou No pour valider"
resultat = raw_input()
if resultat.lower() == 'yes':
ajouttext('/tmp/cron',crontab)
commands.getoutput('crontab /tmp/cron')
print 'Crontab modifié'
else :
sys.exit(2)
elif cron == 2: #suppresion dans le crontab
crontab = commands.getoutput("crontab -l")
crontab = supprimerligner(crontab,filename)
ajouttext('/tmp/cron',crontab)
commands.getoutput('crontab /tmp/cron')
print "Cron de "+sys.argv[0]+ " enlevé"
sys.exit(2)
#Chargement du fichier xml
try:
meteoxml = urllib.urlopen('http://xoap.weather.com/weather/local/'+ ville +'?cc=*&unit=m&dayf=2')
except (IOError, OSError):
print "Probléme de connexion avec weather.com"
sys.exit(2)
document = minidom.parse(meteoxml)
meteoxml.close()
# Récupération du temps
t = document.getElementsByTagName('cc')[0].getElementsByTagName('t')[0].childNodes[0].nodeValue
weather = t.encode('iso-8859-1')
lever = document.getElementsByTagName('loc')[0].getElementsByTagName('sunr')[0].childNodes[0].nodeValue
leverH = lever.split(":")[0]
leverM = lever.split(":")[1].split()[0]
coucher = document.getElementsByTagName('loc')[0].getElementsByTagName('suns')[0].childNodes[0].nodeValue
coucherH = str(int(coucher.split(":")[0]) + 12)
coucherM = coucher.split(":")[1].split()[0]
#Dictionnaire mettant en rapport météo donné par weather.com et nom des images
temps = {"Cloudy":"cloudy","Fair":"fair","Party Cloudy":"partly_cloudy","Shower":"shower","Rain":"rain","Snow":"snow","Storm":"storm","Sunny":"sunny",'Mostly Cloudy':"cloudy","Light Rain":'rain'}
#Génération du background.xml
doc = Document()
def creerNoeud(nom):
noeud = doc.createElement(nom)
return noeud
def creerN(pere,fils,valeur=""):
fils = creerNoeud(fils)
texte = doc.createTextNode(valeur)
fils.appendChild(texte)
pere.appendChild(fils)
# Create balise background
background = doc.createElement("background")
doc.appendChild(background)
# Create balise starttime
starttime = doc.createElement("starttime")
background.appendChild(starttime)
# Create noeud de startime
creerN(starttime,"year","2007")
creerN(starttime,"month","09")
creerN(starttime,"days","26")
creerN(starttime,"hour","07")
creerN(starttime,"minute","00")
creerN(starttime,"second","00")
def creerNStatic(durer,fichier):
static = doc.createElement("static")
background.appendChild(static)
creerN(static,"duration",durer)
creerN(static,"file",fichier)
def creerNTransition(durer,fichier1,fichier2,mode="overlay"):
transition = doc.createElement("transition")
transition.setAttribute("type", mode)
background.appendChild(transition)
creerN(transition,"duration",durer)
creerN(transition,"from",fichier1)
creerN(transition,"to",fichier2)
try:
path = os.path.join(path, temps[weather])
except:
path = os.path.join(path,"snow")
# We start with sunrise at 7 AM. It will remain up for 1 hour.
creerNStatic("3600", path + "1.jpg")
# Sunrise starts to transition to day at 8 AM. The transition lasts for 5 hours, ending at 1 PM.
creerNTransition("18000",path + "1.jpg",path + "2.jpg")
#It's 1 PM, we're showing the day image in full force now, for 2 hours ending at 3 PM.
creerNStatic("7200", path + "2.jpg")
# It's 3 PM, and we're starting to transition to sunset. Transition completes at 6 PM. -->
creerNTransition("10800",path + "2.jpg",path + "3.jpg")
# It's 6 PM, and it's sunset, for an hour. Ends at 7. -->
creerNStatic("3600", path +"3.jpg")
#It's 7 PM and it's going to start to get darker. This will transition for 3 hours up until 10pm. -->
creerNTransition("10800",path + "3.jpg",path + "4.jpg")
# It's 10pm. It'll stay dark for 7 hours up until 5 AM. -->
creerNStatic("25200", path + "4.jpg")
#It's 5 AM. We'll start transitioning to sunrise for 2 hours up until 7 AM. -->
creerNTransition("7200",path + "4.jpg",path + "1.jpg")
f = open(os.path.join(fileprog,'background.xml'), 'w')
f.write(doc.toxml())
f.close()