May-20-2018, 05:58 PM
There are 2 ways you can do this:
1) Check if the file exist and then open it (typical from other languages like C)
2) try to open it and capture the the error ("ask forgiveness not permission", normal in languages with exceptions like python)
The 2nd one has also big advantages when you add security concerns...
In this case your code can be rewritten as:
1) Check if the file exist and then open it (typical from other languages like C)
2) try to open it and capture the the error ("ask forgiveness not permission", normal in languages with exceptions like python)
The 2nd one has also big advantages when you add security concerns...
In this case your code can be rewritten as:
def read_ds18b20(sensorid): """ Functon reads DS15B20 sensor """ device = f"/sys/bus/w1/devices/{sensorid}/w1_slave" try: # No need to close, the with block does it for us... with open(device, 'rt') as tfile: text = tfile.read() except FileNotFoundError: # Things to do when the sensor id is invalid... # I just going to return None. return None except PermissionError: # The file exists, but the user is not in the right group print(f"You must be in the right group to access:\n{device}") # Just continue with the error... raise # Ok, everything was correct, let's continue # Select 21st word starting from 0. sensor_data =text.split(" ")[20] # Remove 't=' and make floating. temp = float(sensor_data[2:]) / 1000 #return rounded to 1 decimal return round(temp, 1)I am using 2 features that are from recent versions of python, the string interpolation
f"bla bla {variable} bla bla"
that you can change it to "bla bla {} bla bla".format(variable)
and the new exceptions FileNotFoundError and PermissionError... if your python is too old and returns other exception, just experiment from the terminal and use the proper ones...