Python Forum
Thread Rating:
  • 2 Vote(s) - 3.5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Check presence of a file
#6
It is better always to keep the code in a single point (don't repeat yourself) in python you can always use the import machinery to do this.
The only problem is that when you "import" the scripts is executed, so it is common to guard the run part with the __main__ trick.
In your case, there is some mix between proper functions and data, but if you modify the read_MCP to request the spi from the arguments you can store the 2 functions in a separate file:
#!/usr/bin/env python

# This shall be in a file at the same folder as all your programs
# I used low_level.py, but you can have more imagination than me...

import RPi.GPIO as GPIO


def read_MCP(spi, sensorid):         #Function reads MCP3008.
        adc = spi.xfer2([1,(8+sensorid)<<4,0],20000)
        adcread = ((adc[1]&3) << 8) + adc[2]
        return adcread
 

def read_ds18b20(sensorid):     #Function reads DS18B20 sensor.
        device="/sys/bus/w1/devices/"+ sensorid +"/w1_slave"
        try:
            with open (device) as tfile:
                text=tfile.read()
        except FileNotFoundError:
            GPIO.output(25,True)
            notemp = 9999
            return notemp
        sensor_data =text.split(" ")[20]    #Select 21st word start with zero.
        # Haal 't=' weg en maak floating
        temp_raw = float(sensor_data[2:])   #Remove 'T="and make floating.    
        #print (temp_raw)
        temp = temp_raw
        digitemp = '%.1f' % temp            #Round to one decimal.
        return digitemp

def _test():
    # Define here if you want some simple tests to check your functions
    # You can run it as python low_level.py
    pass

if __name__ == '__main__':
    # This part runs only when this script is the main script, not when imported from other
    _test()
Then in your other scripts can import from this other -imagine you call it low_level.py) with from low_level import read_MCP, read_ds18b20
Now your main script will be:
#!/usr/bin/env python
 
      #Versie 2.3; 21mei2018
      #Dit programma leest elke sensor apart uit en slaat aan het einde
      #de resultaten op in een csv file.
      #Importeer benodigde libraries.
      #21/05File not found opgelost.
 
import sys
import time
import csv
import os
import spidev
import RPi.GPIO as GPIO

from low_level import read_MCP, read_ds18b20

spi = spidev.SpiDev()
spi.open(0,0)
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(22,GPIO.IN)
GPIO.setup(27,GPIO.OUT)
GPIO.setup(23,GPIO.OUT)
GPIO.setup(24,GPIO.OUT)
GPIO.setup(25,GPIO.OUT)
     
datum = (time.strftime('%d/%m/%Y'))     # Define date/time variables.
tijd = (time.strftime('%H:%M:%S'))
 
GPIO.output(25,False)                   #reset FileNotFound LED
 
while True:
 
    while True:
 
        time.sleep(1)
        if GPIO.input(22):          #Contact key is ON
            GPIO.output(27,True)    #Turn on LED indicator.
            break
        else:                       #Contact key is dus OFF
            GPIO.output(27,False)   #LED indicator OFF
            print ('Schakelaar is UIT')
 
# Checked water level BB with key OFF
                #Check watersensor SB, channel0 of ADC.    
            level = read_MCP(spi, 0)
            level_SB = round(level,1)
            print (level_SB)
             
# Turn on the SB pump if value > 510.
            if (level_SB) > 510:
                GPIO.output(23,GPIO.HIGH)    #LED/pomprelais SB ON.
            else:
                GPIO.output(23,GPIO.LOW)     #LED/pomprelais SB OFF.
 
               #Check watersensor BB, channel1 of ADC.
            level =read_MCP(1)
            level_BB= round(level,1)
            print (level_BB)
             
# Turn on the BB pump if value > 510
            if (level) > 510:
                GPIO.output(24,GPIO.HIGH)    #LED/pomprelais BB ON.
            else:
                GPIO.output(24,GPIO.LOW)     #LED/pomprelais BB OFF.            
 
# Exec DS18B20 function for sensorID's below.
    temp1 = float(read_ds18b20('28-000009aeba12'))      #Motor 1
    temp2 = float(read_ds18b20('28-000009aeba12'))      #Motor 2
    temp3 = float(read_ds18b20('28-000009adc801'))      #Buitentemperatuur
 
# Define 'lijst'.   
    lijst = [0,0,0,0,0,0,0,0]
 
# Exec function 'read_temp36' for each ADC channel.
    for offset in range(0,8):
        adcread = read_MCP(spi, offset)
        print (adcread)
        result = (adcread*330)/float(1024)
        lijst[offset] = adcread
        offset +=1              #Decrease offset by 1
        
    data = [datum,tijd,temp1,temp2,temp3,round(lijst[0],1),round(lijst[1],1),round((((lijst[2]*3.3/1024)-0.52)/0.08),1),round((((lijst[3]*3.3/1024)-0.52)/0.08),1)]
 
# lijst 0 is watersensor SB, lijst 1 is idem BB, lijst 3 is stroom SB, lijst 4 is stroom BB
 
# Turn on the SB pump if value > 510.    if (lijst[0]) > 510:
        GPIO.output(23,GPIO.HIGH)       #LED/pomprelais SB ON
    else:
        GPIO.output(23,GPIO.LOW)        #LED/pomprelais SB ON
 
# Turn on the BB pump if value > 510.
    if (lijst[1]) > 510:
        GPIO.output(24,GPIO.HIGH)       #LED/pomprelais BB ON
    else:
        GPIO.output(24,GPIO.LOW)        #LED/pomprelais BB ON
 
    print (data)
 
        #Output naar csv file
    #csvfile = "/home/pi/programs/testdata.csv"
    #with open (csvfile,'a') as output:
    #    writer = csv.writer(output, delimiter = ',' ,lineterminator = '\n')
    #    writer.writerow(data)
         
    time.sleep(0.5)
You now can re-use that functions from other scripts. In general is always better to keep the things in a single part than abuse from the copy-paste or create a gargantuous script that tries to do everything and each time you try to fix one of the functions you break other three (Keep it simple....)
If you finish having too many small functions and want to organise them properly. you can create easily a package... but that is more advanced python.
Reply


Messages In This Thread
Check presence of a file - by Steffenwolt - May-20-2018, 04:28 PM
RE: Check presence of a file - by killerrex - May-20-2018, 05:58 PM
RE: Check presence of a file - by Steffenwolt - May-21-2018, 09:37 AM
RE: Check presence of a file - by buran - May-21-2018, 09:38 AM
RE: Check presence of a file - by Steffenwolt - May-21-2018, 03:58 PM
RE: Check presence of a file - by killerrex - May-21-2018, 05:43 PM
RE: Check presence of a file - by Steffenwolt - May-23-2018, 08:31 PM
RE: Check presence of a file - by killerrex - May-24-2018, 07:50 AM
RE: Check presence of a file - by Steffenwolt - May-25-2018, 07:04 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  please check this i wanna use a csv file as a graph xCj11 5 1,617 Aug-25-2022, 08:19 PM
Last Post: deanhystad
  check if a file exist on the internet and get the size kucingkembar 6 1,908 Apr-16-2022, 05:09 PM
Last Post: kucingkembar
  Code to check folder and sub folders for new file and alert fioranosnake 2 2,064 Jan-06-2022, 05:03 PM
Last Post: deanhystad
  Check last time file was accessed Pavel_47 4 2,930 Jun-01-2021, 05:47 PM
Last Post: Yoriz
  How to check if a file has finished being written leocsmith 2 8,119 Apr-14-2021, 04:21 PM
Last Post: perfringo
  Check if a file exists. Pedroski55 5 3,417 Sep-08-2020, 10:01 AM
Last Post: Pedroski55
  How to check to see a dbf file is EOF ? DarkCoder2020 0 1,785 Jun-16-2020, 05:03 PM
Last Post: DarkCoder2020
  Building a script to check size of file upon creation mightyn00b 2 2,451 Apr-04-2020, 04:39 AM
Last Post: Larz60+
  MySql - Loop - CHeck File gcclinux 1 2,153 Nov-30-2019, 11:51 AM
Last Post: ThomasL
  Checking the presence of label using pywinauto module Malt 0 1,997 Jul-26-2019, 09:06 AM
Last Post: Malt

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020