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 有大用
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()
if "ok" in output:
return False
if not output:
return True
if "error" in output:
return True
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:使用双反斜杠
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:简化查询(避免正则表达式)
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()
if "ok" in output and "bluetooth" in output:
return False
return True
if is_bluetooth_disabled():
print("蓝牙被禁用")
else:
print("蓝牙已启用")
改进建议
您的代码逻辑已经很不错了,但还可以进一步优化:
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
)
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("蓝牙已启用")
这个改进版本:
使用原始字符串避免转义问题
添加了异常处理
设置了超时时间
简化了查询逻辑
使用UTF-8编码(更通用)
推荐使用方案1或方案3的修复方法。