Detect if I am running from maya?

Wouldn’t something like this do the trick for a one-time check?

try:
    import maya.cmds as cmds
except ImportError:
    # no maya
else:
    # If for some reason you had the maya module in your sys.path
    try:
        if cmds.about(batch=True):
            # in batch mode
    except AttributeError:
        # cmds module isn't fully loaded/populated (which only happens in batch, maya.standalone, or maya GUI)
        # no maya