Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 235
Bálint Balina Avatar asked Sep 12 '26 20:09

Bálint Balina


2 Answers

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

like image 113
Nick Bastin Avatar answered Sep 15 '26 09:09

Nick Bastin


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', 'aarch64')
like image 28
driedler Avatar answered Sep 15 '26 10:09

driedler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!