pythondjangoraspberry-pi3

Raspberry pi, python, detect os


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

Solution

  • 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).