Detect WSL from Python in Windows

It’s also straightforward to detect if

  • running inside WSL
  • WSL is available

These functions use only Python standard library modules.

Detect if inside WSL

This function detects if Python is running in WSL.

from platform import uname

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

    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