Reputation: 90
I am developing a django app which will run on the raspberry pi 3 in production.
I must know at the start of the app if its running on raspberry, or in dev environment. In dev i use fake sensor data instead of the pins.
Until now i used this method:
from sys import platform as _platform
test_environment = "win" in _platform or "darwin" in _platform
This was working nice for both my pc and mac, but now i would like to deploy this to an ubuntu webserver online. Raspbian is also a linux dist, so i need something else.
This is my currently working solution, but it hurts me deep inside. Any suggestion to make it better?
try:
import RPi.GPIO as gpio
test_environment = False
except:
test_environment = True
Upvotes: 2
Views: 2603
Reputation: 4190
There's good info in this thread: https://raspberrypi.stackexchange.com/questions/5100/detect-that-a-python-program-is-running-on-the-pi
import platform
def is_raspberry_pi() -> bool:
return platform.machine() in ('armv7l', 'armv6l')
Upvotes: 1
Reputation: 31339
Your solution is basically fine - I would improve it to just catch the specific error you're really looking for:
try:
import RPi.GPIO as gpio
test_environment = False
except (ImportError, RuntimeError):
test_environment = True
This way if some other error occurs (out of memory, a poorly timed control-c, etc.), you won't believe you are in a test environment when you're not. You could also add more checks just to be sure (e.g. only check for import RPi.GPIO
if you're on linux).
Upvotes: 3