How to check in a script if it is being run as part of a snap?

We have a generic script that should use one port if it’s running “normally” and if it’s being run as a snap, it should use another port. I do not want to duplicate the whole script for two versions, but rather - have runtime detection in the script and use the correct port.

Is there some environment variable or similar, which one could reliably investigate and change the port accordingly?

Well, reading the docs - https://snapcraft.io/docs/environment-variables - I would assume if environment variable $SNAP exists, the script is most likely running as part of a snap?

Yes, just pick one of the snap-specific env variables. I use SNAP_NAME in my python script to check if its value matches my snap’s name. I have os.environ.get() return empty string when the variable isn’t set. Example:

is_snap = os.environ.get('SNAP_NAME', '') == 'my snap name'

1 Like