Determine if a Python file is running in Blender?
edit: This answer will not work since Blender 2.91 because the meaning of sys.executable changed, see https://developer.blender.org/rB04c5471ceefb41c9e49bf7c86f07e9e7b8426bb3.

I found an example of this on the &quot;Blender as a python module&quot; wiki: https://github.com/TylerGubala/blenderpy/wiki/Caveat---Importing-Addons#development-of-new-gui-addons
Their suggestion is to test os.path.basename(sys.executable) for a prefix of &quot;blender&quot; vs &quot;python&quot;, eg.
in_blender = os.path.basename(sys.executable or '').lower().startswith('blender')

(Testing sys.executable is a little better than sys.argv[0]. A script with a shebang line called like ./blender-script.py will have a sys.argv[0] of &quot;./blender_script.py&quot; (giving a false positive), while its sys.executable will still be the path to the python interpreter.)
Another idea is to test that sys.executable is the same as bpy.app.binary_path
try:
    import bpy
    in_blender = (sys.executable == bpy.app.binary_path)
except ModuleNotFoundError:
    in_blender = False