欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

is_bluetooth_disabled_ok.py:5: SyntaxWarning: invalid escape sequence '\(' ['powershell', '-Command', 'Get-PnpDevice -Class Bluetooth | Where-Object { $_.FriendlyName -match "Bluetooth\(R\)" deepseek chatgpt 有大用 有大大用

        def is_bluetooth_disabled():

            result = subprocess.run(

                ['powershell', '-Command', 'Get-PnpDevice -Class Bluetooth | Where-Object { $_.FriendlyName -match "Bluetooth\(R\)" } | Format-Table -HideTableHeaders Status'],

                capture_output=True, text=True, encoding='mbcs', errors='ignore'

            )

C:\Users\aaa\PycharmProjects\pythonProject\bluetooth\is_bluetooth_disabled_ok.py:5: SyntaxWarning: invalid escape sequence '\('

  ['powershell', '-Command', 'Get-PnpDevice -Class Bluetooth | Where-Object { $_.FriendlyName -match "Bluetooth\(R\)" } | Format-Table -HideTableHeaders Status'],


您的代码有一个小的语法警告,关于正则表达式中的转义字符问题。在Python字符串中,\是转义字符,所以\\(中的第一个\会被解释为转义字符。有几种方法可以修复这个问题:

修复方案

方案1:使用原始字符串(推荐)# ok  有大用

python                                
import subprocess

def is_bluetooth_disabled():
    result = subprocess.run(
        ['powershell', '-Command', r'Get-PnpDevice -Class Bluetooth | Where-Object { $_.FriendlyName -match "Bluetooth\(R\)" } | Format-Table -HideTableHeaders Status'],
        capture_output=True, text=True, encoding='mbcs', errors='ignore'
    )

    output = result.stdout.lower().strip()

    # 如果包含 OK 就是启用
    if "ok" in output:
        return False

    # 没有输出蓝牙,视为禁用
    if not output:
        return True

    # 任意一行含 error → 禁用
    if "error" in output:
        return True

    # 全部都是 unknown → 也视为禁用
    lines = [line.strip() for line in output.splitlines() if line.strip()]
    if all(line == "unknown" for line in lines):
        return True

    # 其他情况 → 按禁用处理
    return True

if is_bluetooth_disabled():
    print("蓝牙被禁用")
else:
    print("蓝牙已启用")
                   

方案2:使用双反斜杠

python                                
result = subprocess.run(
    ['powershell', '-Command', 'Get-PnpDevice -Class Bluetooth | Where-Object { $_.FriendlyName -match "Bluetooth\\(R\\)" } | Format-Table -HideTableHeaders Status'],
    capture_output=True, text=True, encoding='mbcs', errors='ignore'
)
                   

方案3:简化查询(避免正则表达式)

python                                
import subprocess

def is_bluetooth_disabled():
    result = subprocess.run(
        ['powershell', '-Command', 'Get-PnpDevice -Class Bluetooth | Where-Object Status -eq "OK"'],
        capture_output=True, text=True, encoding='mbcs', errors='ignore'
    )

    output = result.stdout.lower().strip()

    # 如果有状态为OK的蓝牙设备,就认为蓝牙已启用
    if "ok" in output and "bluetooth" in output:
        return False
    
    return True

if is_bluetooth_disabled():
    print("蓝牙被禁用")
else:
    print("蓝牙已启用")
                   

改进建议

您的代码逻辑已经很不错了,但还可以进一步优化:

python                                
import subprocess

def is_bluetooth_disabled():
    try:
        result = subprocess.run(
            ['powershell', '-Command', r'Get-PnpDevice -Class Bluetooth | Where-Object Status -eq "OK"'],
            capture_output=True, text=True, encoding='utf-8', timeout=10
        )
        
        # 检查是否有状态为OK的蓝牙设备
        if result.returncode == 0 and "ok" in result.stdout.lower():
            return False
        else:
            return True
            
    except (subprocess.TimeoutExpired, Exception):
        # 如果执行失败,保守地返回禁用状态
        return True

if is_bluetooth_disabled():
    print("蓝牙被禁用")
else:
    print("蓝牙已启用")
                   

这个改进版本:

  1. 使用原始字符串避免转义问题

  2. 添加了异常处理

  3. 设置了超时时间

  4. 简化了查询逻辑

  5. 使用UTF-8编码(更通用)

推荐使用方案1或方案3的修复方法。


普通分类: