SoFunction
Updated on 2025-04-07

Lightning interface detection using python

Functional Overview

This Python script is used to detect the system's Thunderbolt interface support, including:

Detect whether the system has a lightning controller

Detect Type-C/Thunderbolt ports

Identify the lightning interface version (Thunderbolt 1-5)

Show theoretical transmission speed

List connected lightning equipment

Code structure

1. Basic support for detection functions

def check_thunderbolt_support() -> Dict[str, bool]

This function checks the system's lightning support through the Windows Management Instrumentation (WMI) command and returns a dictionary containing the following information:

has_controller: Is there a lightning controller

has_port: Is there a Type-C/thunderbolt port

is_active: Is the lightning interface active?

2. Version detection function

def get_thunderbolt_version() -> Dict[str, str]

Identify the lightning version supported by the system, return the version number and the corresponding theoretical speed:

  • Thunderbolt 5: 80 Gbps (two-way), up to 120 Gbps (one-way)
  • Thunderbolt 4: 40 Gbps
  • Thunderbolt 3: 40 Gbps
  • Thunderbolt 2: 20 Gbps
  • Thunderbolt 1: 10 Gbps

3. Get the function in detail

def get_detailed_thunderbolt_info() -> List[Dict[str, str]]

Get detailed information about all connected lightning equipment, including:

  • Device name
  • Manufacturer Information
  • Equipment Status

4. Status Report Function

def print_thunderbolt_status()

Generate a complete lightning interface support status report, including:

  • Host lightning support status
  • Host Lightning Version Information
  • List of connected devices
  • Notes on using

How to use

Run the script directly:

python thunderbolt_check.py

Import as a module:

from thunderbolt_check import check_thunderbolt_support, get_thunderbolt_version

# Check basic supportsupport_info = check_thunderbolt_support()

# Get version informationversion_info = get_thunderbolt_version()

Things to note

1. The actual transmission speed depends on:

The lightning version supported by the host

Thunderbolt version supported by the connected device

It will actually run at a lower speed of both

2. If the detection result shows a lightning port but is not activated:

Check the BIOS settings for lightning support options

Make sure the latest lightning driver is installed

3. Version speed comparison table:

Version Theoretical speed Remark
Thunderbolt 5 80/120 Gbps Expected to be launched by the end of 2024
Thunderbolt 4 40 Gbps More stringent certification requirements
Thunderbolt 3 40 Gbps The most widely used version
Thunderbolt 2 20 Gbps Older version
Thunderbolt 1 10 Gbps The earliest version

Technical implementation details

Use the subprocess module to execute WMI commands

Parse device information through regular expressions

Support Chinese and English device description recognition

Exception handling ensures stable operation of the program

Possible errors and solutions

"An error occurred while obtaining the lightning version information"

Make sure to run with administrator privileges

Check whether the WMI service is running normally

"Connected lightning device not detected"

Confirm whether the device is connected correctly

Check whether the device driver is installed correctly

Complete code

import subprocess
import re
from typing import Dict, List, Tuple

def check_thunderbolt_support() -> Dict[str, bool]:
    """
    Check whether the system supports lightning interface
    
    Returns:
        Dict[str, bool]: Dictionary containing information on lightning interface support
        {
            'has_controller': bool,  # Is there a lightning controller            'has_port': bool,        # Is there a lightning port            'is_active': bool        # Is the lightning interface activated?        }
    """
    result = {
        'has_controller': False,
        'has_port': False,
        'is_active': False
    }
    
    try:
        # Check Type-C and Thunderbolt support in USB controller        usb_controllers = subprocess.check_output(
            ["wmic", "path", "Win32_USBController", "get", "name,manufacturer"], 
            encoding='gbk'
        ).strip()
        
        if "Type-C" in usb_controllers:
            result['has_port'] = True
        
        # Check the lightning equipment in the device manager        tb_devices = subprocess.check_output(
            ["wmic", "path", "Win32_PnPEntity", "where", 
             "caption like '%Thunderbolt%' OR caption like '%Thunderbolt%'", 
             "get", "caption,status"], 
            encoding='gbk'
        ).strip()
        
        if tb_devices and len(tb_devices.split('\n')) > 1:
            result['has_controller'] = True
            # Check if there is any lightning equipment in operation            if "OK" in tb_devices or "normal" in tb_devices:
                result['is_active'] = True
        
        # Extra check for lightning controllers in PCI devices        pci_devices = subprocess.check_output(
            ["wmic", "path", "Win32_PnPEntity", "where", 
             "deviceid like '%PCI%'", "get", "caption"],
            encoding='gbk'
        ).strip()
        
        if any(x in pci_devices.lower() for x in ['thunderbolt', 'Thunder']):
            result['has_controller'] = True
            
    except Exception as e:
        print(f"An error occurred while checking for lightning support: {e}")
    
    return result

def get_detailed_thunderbolt_info() -> List[Dict[str, str]]:
    """
     Get detailed lightning interface information
    
     Returns:
         List[Dict[str, str]]: A list containing all lightning equipment information
     """
    devices = []
    try:
        # Obtain all possible lightning-related equipment        cmd_output = subprocess.check_output(
            ["wmic", "path", "Win32_PnPEntity", "where",
             "caption like '%Thunderbolt%' OR caption like '%Thunderbolt%' OR caption like '%Type-C%'",
             "get", "caption,manufacturer,status,deviceid"],
            encoding='gbk'
        ).strip()
        
        # parse output        lines = cmd_output.split('\n')
        if len(lines) > 1:  # Skip the title line            headers = [().lower() for h in lines[0].split('  ') if ()]
            for line in lines[1:]:
                if ():
                    # Split and filter empty strings with multiple spaces                    values = [() for v in (r'\s{2,}', line) if ()]
                    if len(values) >= len(headers):
                        device = dict(zip(headers, values))
                        (device)
    
    except Exception as e:
        print(f"An error occurred while obtaining detailed lightning information: {e}")
    
    return devices

def get_thunderbolt_version() -> Dict[str, str]:
    """
     Get the version and speed information of the lightning interface
    
     Returns:
         Dict[str, str]: Dictionary containing lightning version and speed information
     """
    version_info = {
        'version': 'Unknown',
        'speed': 'Unknown'
    }
    
    try:
        # Check the description of the lightning device in the Device Manager        tb_devices = subprocess.check_output(
            ["wmic", "path", "Win32_PnPEntity", "where",
             "caption like '%Thunderbolt%' or caption like '%Thunderbolt%'",
             "get", "caption,description"],
            encoding='gbk'
        ).strip()
        
        #Judge version based on description        if 'Thunderbolt 5' in tb_devices or 'Thunder 5' in tb_devices:
            version_info['version'] = 'Thunderbolt 5'
            version_info['speed'] = '80 Gbps (Two-way), Highest120 Gbps (unidirectional)'
        elif 'Thunderbolt 4' in tb_devices or 'Thunder and lightning 4' in tb_devices:
            version_info['version'] = 'Thunderbolt 4'
            version_info['speed'] = '40 Gbps'
        elif 'Thunderbolt 3' in tb_devices or 'Thunder 3' in tb_devices:
            version_info['version'] = 'Thunderbolt 3'
            version_info['speed'] = '40 Gbps'
        elif 'Thunderbolt 2' in tb_devices or 'Thunder 2' in tb_devices:
            version_info['version'] = 'Thunderbolt 2'
            version_info['speed'] = '20 Gbps'
        elif 'Thunderbolt' in tb_devices or 'Thunder' in tb_devices:
            version_info['version'] = 'Thunderbolt 1'
            version_info['speed'] = '10 Gbps'
            
    except Exception as e:
        print(f"获取Thunder and lightningVersion信息时出错: {e}")
    
    return version_info

def print_thunderbolt_status():
    """
     Print the status report for lightning interface support
     """
    print("=" * 50)
    print("Thunderbolt interface support status check report")
    print("=" * 50)
    
    # Check basic support status    support_info = check_thunderbolt_support()
    print("\nHost lightning support situation:")
    print(f"- Thunder and lightning控制器: {'✓ Found' if support_info['has_controller'] else '✗ Not Found'}")
    print(f"- Type-C/Thunder and lightning端口: {'✓ Exist' if support_info['has_port'] else '✗ does not exist'}")
    print(f"- Thunder and lightning接口state: {'✓ Activated' if support_info['is_active'] else '✗ Not activated'}")
    
    # Get and display version information    version_info = get_thunderbolt_version()
    print(f"\nHost Lightning Version Information:")
    print(f"- Version: {version_info['version']}")
    print(f"- Theoretical speed: {version_info['speed']}")
    
    # Get detailed information    detailed_info = get_detailed_thunderbolt_info()
    if detailed_info:
        print("\nConnected lightning equipment:")
        for idx, device in enumerate(detailed_info, 1):
            print(f"\nequipment {idx}:")
            if 'caption' in device:
                print(f"- equipment名称: {device['caption']}")
            if 'manufacturer' in device:
                print(f"- Manufacturer: {device['manufacturer']}")
            if 'status' in device:
                print(f"- state: {device['status']}")
    else:
        print("\nNo connected lightning device detected")
    
    print("\nPrecautions:")
    if not support_info['has_controller']:
        print("- The system may not support the lightning interface")
    if support_info['has_port'] and not support_info['is_active']:
        print("- The lightning interface exists but is not activated, please check the BIOS settings")
    if support_info['has_controller'] and support_info['has_port']:
        print("- The system supports lightning interface. If you encounter any problems, please update the driver")
    print("- Actual transmission speed depends on the minimum lightning version supported by the host and device")

if __name__ == "__main__":
    print_thunderbolt_status()

This is the end of this article about using python for lightning interface detection. For more related python lightning interface detection content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!