• [^] # Re: Est-ce que tu as un message d'erreur ?

    Posté par . En réponse au message Ecriture fichier txt. Évalué à 1.

    Merci a tous Super ça fonctionne .
    J'ai bricolé ce code que j'ai posté , pour essayé de comprendre le fonctionnement de la création et de l’écriture du fichier histINT.

    je pensais pouvoir me débrouiller seul pour adapter ça a mon fichier howonpi .Mais ce n'est pas du tout le cas .

    Pour écrire dans histINT j'ai fais ca .

    sfile.write(get_c_locale_abbrev() + " /" + validatePrint(sensorInfo))

    sensorInfo n'est pas bon , je récupère trop d'information .

    Sat Apr 25 13:10:04 2015 /[['TDS1', '28-000005239592', 'T\xb0Interieure', 19.0]]

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    """
     Scan all sensors from DS18B20.conf
     store data into rrdtool database
     export chart data 
    """
    import locale
    import datetime
    import time
    import subprocess
    import os
    import sys
    import shlex
    import DS18B20
    from re import search
    DS = DS18B20.DS18B20()
    #fonction pour changer le language de la date en anglais
    def get_c_locale_abbrev():
     lc = locale.setlocale(locale.LC_TIME)
     try:
     locale.setlocale(locale.LC_TIME, "C")
     return time.strftime("%a %b %d %H:%M:%S %Y")
     finally:
     locale.setlocale(locale.LC_TIME, lc)
    #first read configuration to get DS18B20 ID and label info
    try:
     fileH = open("/home/www/Graph/DS18B20.conf")
     text = fileH.read()
     fileH.close()
     sensorInfo= [ s.strip().split(',') for s in text.splitlines()]
    except:
     print("Unable to read 'DS18B20.conf'")
     quit()
    NumberOfSensor= len(sensorInfo)
    if NumberOfSensor ==0:
     print("No sensor in configuration file 'DS18B20.conf'. Exit!")
     quit()
    #get Temperature of each sensor
    #add add it up into the sensor Info
    for i in sensorInfo:
     i.append(DS.read(i[1]))
    #let's update the current status file
    #if the value is None just put ---
    def validatePrint(value):
     if value == None:
     return "---"
     else:
     return "{}".format(value)
    #if the value is None tell rrdtool that the value is unknown
    def validateRRD(value):
     if value == None:
     return ":U"
     else:
     return ":{}".format(value)
    ''' **********
     Ici c'est le fichier hist-INT
     ce fichier est créé avec un modulus % 5 de la minute.
     Donc 5 fichier en alternance et le dernier sera un link sur hist-INT
     pour permettre d'utiliser hist-INT sans avoir de problème
     de lecture lorsque le fichier ce fait écrire '''
    #current time
    current_time= datetime.datetime.now()
    histINT = "/home/www/logs/hist-INT"
    #Nom des fichier
    Temp_histINT= histINT + "{}".format(current_time.minute % 5) + ".txt"
    Link_histINT= histINT + ".txt"
    #creation du fichier modulus
    #try:
    if True:
     sfile = open(Temp_histINT,'w')
     sfile.write(get_c_locale_abbrev() + " /" + validatePrint(sensorInfo))
     sfile.close()
     #creation du link os.symlink ne marche pas si le fichier est déja linké
     #os.symlink(Temp_histINT,Link_histINT)
     subprocess.Popen(["/bin/ln","-fs",Temp_histINT,Link_histINT])
    #except:
    # print("unable to create {}".format(Temp_histINT)) 
    webdata = "/home/www/Graph/webdata/"
    currentStatus = webdata + "DS18B20Status.txt"
    try:
     sfile = open(currentStatus,'w')
     for sensor in sensorInfo:
     sfile.write(sensor[0])
     sfile.write("," + sensor[1])
     sfile.write("," + sensor[2])
     sfile.write("," + validatePrint(sensor[3])+ "\n")
     sfile.close()
    except:
     print("unable to create '/home/www/Graph/webdata/DS18B20Status.txt'")
    #now let's insert the result into rrdtool database
    fileRrdTool = "/home/www/Graph/data_DS18B20.rrd"
    #let's fill the command line with the 
    #Current time (Right now)
    rdata = "N"
    #add the sensors result
    for sensor in sensorInfo:
     rdata = rdata + validateRRD(sensor[3])
    #now update the database
    subprocess.Popen(["/usr/bin/rrdtool","update",fileRrdTool,rdata])
    #data Extraction to create data point for the charts.
    #create a function with start and step parameters
    #this way we could create chart with different timing
    def rrdExport(start, step, XMLfile):
     texte = "rrdtool xport -s {0} -e now --step {1} ".format(start, step)
     #let's populate for each sensor
     for i in range(NumberOfSensor):
     texte += "DEF:{}={}:{}:AVERAGE ".format(chr(ord('a')+i),fileRrdTool,sensorInfo[i][0])
     texte += "XPORT:{}:""{}"" ".format(chr(ord('a')+i),sensorInfo[i][2])
     fileout = open(webdata+XMLfile,"w")
     args = shlex.split(texte)
     subprocess.Popen(args,stdout=fileout)
     fileout.close()
    # ok extact 3 hours data
    rrdExport("now-3h",300, "temperature3h.xml")
    #ok 24 hours
    rrdExport("now-24h",900, "temperature24h.xml")
    #ok 48 hours
    rrdExport("now-48h",1800, "temperature48h.xml")
    #ok 1 week
    rrdExport("now-8d",3600, "temperature1w.xml")
    #ok 1 month
    rrdExport("now-1month",14400, "temperature1m.xml")
    #ok 3 month
    rrdExport("now-3month",28800, "temperature3m.xml")
    #ok 1 year
    rrdExport("now-1y",43200, "temperature1y.xml")
    #ok just print on the screen what we have
    for sensor in sensorInfo:
     print("{}:{}".format(sensor[2],validatePrint(sensor[3])))
    #done