I don't understand why "sudo python3 temphumlogger2.py" triggers a module error, while "python3 temphumlogger2.py" executes no problem. Outputs below, and code below that. I want the code to execute automatically on startup, and need to use sudo to do that. I've tried reinstalling the various packages but can't figure out why sudo causes error and without does not?
pi@raspberrypi:~ $ sudo python3 temphumlogger2.py
Traceback (most recent call last):
File "temphumlogger2.py", line 3, in <module>
import adafruit_dht
ModuleNotFoundError: No module named 'adafruit_dht'
pi@raspberrypi:~ $ python3 temphumlogger2.py
waiting 15 mins
Temp: 73.9 F / 23.3 C Humidity: 48.0%
import time
import board
import adafruit_dht
from datetime import datetime
Initial the dht device, with data pin connected to:
dhtDevice = adafruit_dht.DHT22(board.D4)
while True:
try:
# Print the values to the serial port
temperature_c = dhtDevice.temperature
temperature_f = temperature_c * (9 / 5) + 32
humidity = dhtDevice.humidity
with open('/home/pi/thdataupstairs.csv', mode='a') as file_:
file_.write("{},{},{}".format(datetime.now(),temperature_c, humidity))
file_.write("\n")
print("waiting 15 mins")
print(
"Temp: {:.1f} F / {:.1f} C Humidity: {}% ".format(
temperature_f, temperature_c, humidity
)
)
time.sleep(10)
except RuntimeError as error:
# Errors happen fairly often, DHT's are hard to read, just keep going
print(error.args[0])
time.sleep(2.5)
sudo
with python is always a problem (because it is interpreted - Linux prevents permission escalation). https://raspberrypi.stackexchange.com/a/105549/8697 is a much simpler, more reliable solution which doesn't require root privileges. NOTEsudo bash
is a serious security risk. – Milliways Aug 16 '20 at 04:32