@ Didier-T
bonjour au sujet de ton script on peut l'utiliser en mode demon ou pas mais comment peut on le lancer en mise a jour partielle
si je fait mon demon je pourrai changer de compo sans redémarrer
merci
EDIT: j'ai rajouter une condition ça roule
le recmeteo1.py
#! /usr/bin/python3
# -*- coding: utf-8 -*-
# Par Didier-T Forum Ubuntu.fr
# Ajout notification par jpdipsy Forum Ubuntu.fr
# Ajout notification via DBus par ti_tux Forum Ubuntu.fr
# Ajout création repsauv si inexistant par jpdipsy Forum Ubuntu.fr
from socket import timeout
from urllib.request import Request, urlopen, URLError
from os import path, makedirs, system
from time import time, sleep, strftime, localtime
from re import search, compile, findall
from sys import argv
from gc import collect
from bs4 import BeautifulSoup
Version='1.31c'
homedir = path.expanduser('~')
#### initialisation des variables
adressWeb="http://www.accuweather.com/fr/fr/belfort/133341/daily-weather-forecast/133341"
repsauv= "~/essais"
huitHeures="oui"
nbFoisHuit=1
matin="oui"
apresmidi="oui"
soiree="oui"
nuit="oui"
nbJour=1
interval=30
notifi="oui"
externe = None
Id = "sans"
demon = "oui"
fullnotify = "non"
MAJP = "oui"
for a in argv:
if search("adressWeb=", a) is not None:
adressWeb=compile("adressWeb=(.*)").search(a).group(1)
if search("repsauv=", a) is not None:
repsauv=compile("repsauv=(.*)").search(a).group(1)
if search("huitHeures=", a) is not None:
huitHeures=compile("huitHeures=(.*)").search(a).group(1)
if search("nbJour=", a) is not None:
nbJour=compile("nbJour=(.*)").search(a).group(1)
if search("interval=", a) is not None:
interval=compile("interval=(.*)").search(a).group(1)
if search("notify=", a) is not None:
notifi=compile("notify=(.*)").search(a).group(1)
if search("notifyPartielle=", a) is not None:
fullnotify=compile("notifyPartielle=(.*)").search(a).group(1)
if search("matin=", a) is not None:
matin=compile("matin=(.*)").search(a).group(1)
if search("apresmidi=", a) is not None:
apresmidi=compile("apresmidi=(.*)").search(a).group(1)
if search("soiree=", a) is not None:
soiree=compile("soiree=(.*)").search(a).group(1)
if search("nuit=", a) is not None:
nuit=compile("nuit=(.*)").search(a).group(1)
if search("externe=", a) is not None:
externe=compile("externe=(.*)").search(a).group(1)
if search("nbFoisHuit=", a) is not None:
nbFoisHuit=compile("nbFoisHuit=(.*)").search(a).group(1)
if search("id=", a) is not None:
Id=compile("id=(.*)").search(a).group(1)
if search("demon=", a) is not None:
demon=compile("demon=(.*)").search(a).group(1)
if search("MAJP=", a) is not None:
MAJP=compile("MAJP=(.*)").search(a).group(1)
nbJour=int(nbJour)
interval=int(interval)
repsauv=repsauv.replace("~", homedir)
notifi=str.lower(notifi)
fullnotify==str.lower(fullnotify)
huitHeures=str.lower(huitHeures)
nbFoisHuit=int(nbFoisHuit)
MAJP=str(MAJP)
#### fin initialisation des variables
#### Fonction de traitement des fichiers
def traitement(adress, fichier, repsauv):
current_balise=None
x=1
user_agent = 'Mozilla/5.0 (X11; Linux x86_64)'
headers = { 'User-Agent' : user_agent }
while current_balise is None:
response = None
while response is None:
try:
html_page = urlopen(adress, timeout=10)
except (URLError) as error:
print("HTML ", error)
except timeout:
print("erreur timeout acces HTML")
else:
try:
currentCond=html_page.read()
except (URLError) as error:
print("Lecture page ", error)
except timeout:
print("erreur timeout lecture page")
else:
fiche = open("/tmp/page.html", "wb")
fiche.write(currentCond)
fiche.close()
response = "ok"
if response is None:
sleep(2)
fiche = open("/tmp/page.html", "r")
lines = fiche.readlines()
curr = {}
curr[0] = []
curr[1] = []
i=0
for line in lines:
curr[i].append(line)
if search("!-- /.feed-tabs --", line) is not None:
i=1
curr[0] = ''.join(curr[0])
curr[1] = ''.join(curr[1])
soup1 = BeautifulSoup(curr[0])
soup = BeautifulSoup(curr[1])
#si autres que huit heures
table=soup.find_all('table')
current_balise=soup.find(id="details")
information=[]
information.append("")
if search("huitHeures", fichier) is None:
# recherche vent
divs=current_balise.select("[class~=wind-box-lg]")
if len(divs) == 0:
divs=current_balise.select("[class~=wind-box-sm]")
i=0
for div in divs:
i=i+1
ventd=compile("var d = '(.*)';").search(str(div)).group(1).replace("W", "O")
ventf=compile("var s = '(.*)';").search(str(div)).group(1)
information.append("direction"+str(i)+": "+ventd)
information.append("vitesse"+str(i)+": "+ventf)
#info dans l'image
inf=current_balise.select("[class~=info]")
icone=current_balise.select("[class~=icon]")
i=0
#recherche icone
for ic in icone:
i=i+1
information.append("icone"+str(i)+": "+str(ic).replace('<div class="icon i-', '').replace('"></div>', ''))
i=0
#récupération date + historique
if search("Jour", fichier) is not None or search("CC", fichier) is not None:
histo=soup.find(id="feature-history")
#récupération date
date=histo.find_all('th')
jour=compile("(.*)/(.*)/(.*)").search(date[4].get_text())
information.append("jour: "+jour.group(1))
information.append("mois: "+jour.group(2))
information.append("année: "+str(int(jour.group(3))+1))
#récupération historique
hi=histo.select("[class~=hi]")
for v in hi:
hivalue=v.get_text().split("\n")
information.append("maxjour: "+hivalue[2])
information.append("maxnormal: "+hivalue[3])
information.append("maxrecord: "+hivalue[4])
information.append("max1ans: "+hivalue[5])
lo=histo.select("[class~=last]")
for v in lo:
lovalue=v.get_text().split("\n")
information.append("minjour: "+lovalue[2])
information.append("minnormal: "+lovalue[3])
information.append("minrecord: "+lovalue[4])
information.append("min1ans: "+lovalue[5])
#info dans l'image
if search("Jour", fichier) is not None:
infs=inf[0].get_text().split("\n")
information.append("Tempjour: "+findall('-?\d+', infs[0])[0])
information.append("RealFeeljour: "+findall('-?\d+', infs[1])[0])
information.append("Précipitationsjour: "+findall('-?\d+', infs[2])[0])
infs=inf[1].get_text().split("\n")
information.append("Tempnuit: "+findall('-?\d+', infs[0])[0])
information.append("RealFeelnuit: "+findall('-?\d+', infs[1])[0])
information.append("Précipitationsnuit: "+findall('-?\d+', infs[2])[0])
lever_coucher=soup.select("[class~=time-period]")
i=0
for p in lever_coucher:
spans=p.find_all('span')
i=i+1
x=0
for span in spans:
if i == 1:
span_nom="Soleil "
else:
span_nom="Lune "
if search('start', str(span)) is not None:
information.append(span_nom+"lever: "+span.get_text())
if search('time', str(span)) is not None:
information.append(span_nom+"durée: "+span.get_text())
if search('finish', str(span)) is not None:
information.append(span_nom+"coucher: "+span.get_text())
p=current_balise.find_all('p')
i=0
x=0
for pv in p:
i=i+1
if i==5 or i==10:
x=x+1
information.append("cond"+str(x)+": "+pv.get_text())
#localisation si condition courante
if search("CC", fichier) is not None:
# ville=soup1.select("[class~=current-city]")[0].get_text().split(",")[0]
ville=compile(" city: '(.*)',").search(str(soup1)).group(1)
longi=compile("lon: '(.*)',").search(str(soup1)).group(1)
lat=compile("lat: '(.*)',").search(str(soup1)).group(1)
information.append("ville: "+ville)
information.append("lat: "+lat)
information.append("long: "+longi)
#info alerte
response = None
while response is None:
try:
alerte_page=urlopen(adressWeb, timeout=10)
except (URLError) as error:
print("HTML ", error)
except timeout:
print("erreur timeout acces HTML")
else:
try:
alerte=alerte_page.read()
except (URLError) as error:
print("Lecture page ", error)
except timeout:
print("erreur timeout lecture page")
else:
alerte=BeautifulSoup(alerte)
alerte=alerte.select("[class~=fc-status]")
if str(alerte) != "[]":
information.append("alerte: "+alerte[0].get_text().replace('\n', '').replace("\r", ""))
else:
information.append("alerte: RAS")
response = "ok"
if response is None:
sleep(2)
#info dans l'image
inf=inf[0].get_text()
cond=inf[:inf.find(findall('-?\d+', inf)[0])]
inf=inf.replace(cond, "")
infs=inf.split(" ")
information.append("cond:"+cond)
information.append("Temp: "+infs[0])
information.append("RealFeel: "+infs[2])
if search("Matin", fichier) is not None or search("AM", fichier) is not None or search("Soiree", fichier) is not None or search("Nuit", fichier) is not None:
infs=inf[0].get_text().split("\n")
i=0
infsc=["","","",""]
for inf in infs:
if inf!="":
infsc[i]=inf
i=i+1
information.append("cond:"+infsc[0])
information.append("max: "+infsc[1])
information.append("min: "+infsc[2].replace("Mn ", ""))
information.append("RealFeelmax: "+findall('-?\d+', infsc[3])[0])
information.append("RealFeelmin: "+findall('-?\d+', infsc[3])[1])
#info conditions générales
cc=current_balise.find_all('li')
for inf in cc:
inf=inf.get_text()
inf=inf.replace(compile('^ *').search(inf).group(0), "").replace("\n", "")
if search(":", inf) is not None:
information.append(inf)
elif search("Jour", fichier) is not None:
i=0
cc=current_balise.find_all('li')
for inf in cc:
inf=inf.get_text()
inf=inf.lstrip().replace("\n", "").replace(" \r", "")
if search(": ", inf) is not None:
i=i+1
if i <= 7:
inf=inf.replace(":", " jour:")
else:
inf=inf.replace(":", " nuit:")
information.append(inf)
else:
cc=current_balise.find_all('li')
for inf in cc:
inf=inf.get_text()
inf=inf.replace(compile('^ *').search(inf).group(0), "").replace("\n", "")
if search(":", inf) is not None:
information.append(inf)
information.append(str(int(time())))
else:
#recherche icones huit heures
rows = table[0].findAll('tr')
x=0
for tr in rows:
cols = tr.findAll('td')
texte_tr=tr.text.split("\n")[1].replace("\n", "")
i=0
for td in cols:
i=i+1
texte_bu = td.text.replace("\n", "").replace(chr(160), "")
if texte_bu != "" :
if texte_tr == chr(160) and x < len(cols):
information.append("Heure"+str(i)+": "+texte_bu)
x=x+1
elif texte_tr != chr(160):
information.append(texte_tr+str(i)+": "+texte_bu)
icone=table[0].find_all('div')
i=0
for ic in icone:
i=i+1
ico="icone"+str(i)+": "+str(ic).replace('<div class="icon i-', '')
fin=compile('">(.*)div>').search(ico).group(1)
information.append(ico.replace('">'+fin+'div>', ''))
if i == 8:
break
fiche = open(fichier, "w")
# fiche.write(current_balise.prettify())
information = '\n'.join(information)
fiche.write(information)
fiche.close()
collect()
#### fin Fonction de traitement des fichiers
#### Mise en tache de fond
def demonise(ent, id1, id2, huitHeures, nbJour, interval, nbFoisHuit, Id, demon, MAJP):
dem=time()-(60*60)
misajour=1
while 1 :
heure=time()
if huitHeures=="oui":
x=0
while x<nbFoisHuit:
h=(x*8)+int(strftime('%H', localtime()))
x=x+1
traitement(ent+nb1+'/hourly-weather-forecast/'+nb2+'?hour='+str(h), repsauv+"/huitHeures"+str(x), repsauv)
print("huitHeures "+str(x)+" Ok")
if heure-dem >= 60*60 and MAJP=="oui":
x=0
while x<nbJour:
x=x+1
traitement(ent+nb1+'/daily-weather-forecast/'+nb2+"?day="+str(x), repsauv+"/Jour"+str(x), repsauv)
print("Jour "+str(x)+" Ok")
if matin=="oui":
traitement(ent+nb1+'/morning-weather-forecast/'+nb2+"?day="+str(x), repsauv+"/Matin"+str(x), repsauv)
print("Matin "+str(x)+" Ok")
if apresmidi=="oui":
traitement(ent+nb1+'/afternoon-weather-forecast/'+nb2+"?day="+str(x), repsauv+"/AM"+str(x), repsauv)
print("AM "+str(x)+" Ok")
if soiree=="oui":
traitement(ent+nb1+'/evening-weather-forecast/'+nb2+"?day="+str(x), repsauv+"/Soiree"+str(x), repsauv)
print("Soiree "+str(x)+" Ok")
if nuit=="oui":
traitement(ent+nb1+'/overnight-weather-forecast/'+nb2+"?day="+str(x), repsauv+"/Nuit"+str(x), repsauv)
print("Nuit "+str(x)+" Ok")
dem=heure
traitement(ent+nb1+'/current-weather/'+nb2, repsauv+"/CC", repsauv)
print("CC Ok")
if externe is not None:
system(externe)
fin=time()
duree=fin-heure
if notifi == "oui":
notify2.init('Recmeteo.py')
if heure-dem == 0:
mess=notify2.Notification('Recmeteo.py v'+Version, 'Météo : mise à jour complète terminée\n en '+str(round(duree,2))+' secondes', 'dialog-information')
mess.show()
else:
if fullnotify == "oui" :
mess=notify2.Notification('Recmeteo.py v'+Version, 'Météo : mise à jour partielle terminée\n en '+str(round(duree,2))+' secondes', 'dialog-information')
mess.show()
start=heure
pause=60*interval-int(duree)
if pause < 0:
pause=interval
print("mise a jour en : "+str(duree))
if demon == "non":
print("Mode démon non utilisé\nfin de recmeteo.py")
exit()
collect()
sleep(pause)
if Id != "sans":
if not path.exists("/proc/"+Id):
exit()
### Initialiation de DBus pour les notifications
if notifi == "oui":
import notify2
### Vérification répertoire
if not path.exists(repsauv):
makedirs(repsauv)
#### Lancement du script et initialisation de la tache de fond
nb1=findall('\d+', adressWeb)[0]
nb2=findall('\d+', adressWeb)[1]
ent=adressWeb[:adressWeb.find(nb1)]
fin=adressWeb.replace(ent+nb1, "")
fin=fin.replace(fin[:fin.find(nb2)]+nb2, "")
nb2=nb2+fin
print("Version =", Version)
demonise(ent, nb1, nb2, huitHeures, nbJour, interval, nbFoisHuit, Id, demon, MAJP)