Detect WSL from Python in Windows

It’s trivial to detect if one is running inside WSL. It’s also straightforward to detect if WSL is available and working on a Windows PC. These functions are using only Python standard library modules.

Detect if inside WSL

This function detects if Python is running in WSL.

import uname

def in_wsl() -> bool:
    WSL is thought to be the only common Linux kernel with Microsoft in the name.

    return 'Microsoft' in uname().release

Detect WSL from Windows

import os
import shutil

def wsl_available() -> bool:
    heuristic to detect if Windows Subsystem for Linux is available.

    Uses presence of /etc/os-release in the WSL image to say Linux is there.
    This is a de facto file standard across Linux distros.
    if == "nt":
        wsl = shutil.which("wsl")
        if not wsl:
            return False
        # can't read this file or test with
        # pathlib.Path('//wsl$/Ubuntu/etc/os-release').
        # A Python limitation?
        ret =["wsl", "test", "-f", "/etc/os-release"])
        return ret.returncode == 0

    return False