我的腳本通過第一個回圈查找某些藍牙狀態標準(如果它已打開并且沒有連接設備),然后休眠 10 秒以允許用戶更改藍牙狀態,然后在執行提示之前再次檢查相同的標準。
我不明白的是,當我在等待期(10 秒)結束之前運行代碼并更改狀態時,它仍然在第二個 if 陳述句中運行代碼。
def bluetoothLoop():
while True:
def bluetooth_msg():
BT_state = subprocess.run(['''system_profiler SPBluetoothDataType'''], shell=True, capture_output=True, encoding="utf", errors="ignore")
BT_state = BT_state.stdout
sound = "Blow"
title = "TURN OFF BLUETOOTH"
message = "Wasting energy"
if "State: On" in BT_state and not " Connected:" in BT_state:
time.sleep(10)
if "State: On" in BT_state and not " Connected:" in BT_state:
command = f'''
osascript -e 'display notification "{message}" with title "{title}" sound name "{sound}"'
'''
os.system(command)
bluetooth_msg()
uj5u.com熱心網友回復:
您在睡眠前運行subprocess以獲取 ,BT_state但在睡眠后不再運行它,因此變數BT_state不會更新。實際上,您正在檢查同一件事兩次。
我在下面重構了您的代碼以分離出不同的部分,希望更容易看到發生了什么。
import subprocess
import time
def check_bt_status():
output = subprocess.check_output(["system_profiler",
"SPBluetoothDataType"])
return all([b"Bluetooth Power: On" in output,
b"Connected: Yes" not in output])
def show_msg(title, message, sound):
apple_script = (f'display notification "{message}"'
f'with title "{title}" '
f'sound name "{sound}"')
subprocess.check_output(["osascript", "-e", apple_script])
def bluetooth_loop():
while True:
if check_bt_status():
show_msg("TURN OFF BLUETOOTH", "Wasting energy", "Blow")
time.sleep(10)
if __name__ == "__main__":
bluetooth_loop()
將 BT 狀態邏輯放在一個單獨的方法中意味著如果您需要更改該邏輯,那么您只需在一個地方更改它。
uj5u.com熱心網友回復:
睡眠 10 秒后,您不會重繪 狀態。嘗試
if "State: On" in BT_state and not " Connected:" in BT_state:
time.sleep(10)
BT_state = subprocess.run(['''system_profiler SPBluetoothDataType'''], shell=True, capture_output=True, encoding="utf", errors="ignore")
BT_state = BT_state.stdout
if "State: On" in BT_state and not " Connected:" in BT_state:
command = f'''
osascript -e 'display notification "{message}" with title "{title}" sound name "{sound}"'
'''
os.system(command)
您甚至可以通過以下方式清理代碼
def bluetoothLoop():
BT_state = subprocess.run(['''system_profiler SPBluetoothDataType'''], shell=True, capture_output=True, encoding="utf", errors="ignore")
BT_state = BT_state.stdout
def bluetooth_msg():
sound = "Blow"
title = "TURN OFF BLUETOOTH"
message = "Wasting energy"
command = f'''
osascript -e 'display notification "{message}" with title "{title}" sound name "{sound}"'
'''
os.system(command)
while "State: On" in BT_state and not " Connected:" in BT_state:
bluetooth_msg()
time.sleep(10)
BT_state = subprocess.run(['''system_profiler SPBluetoothDataType'''], shell=True, capture_output=True, encoding="utf", errors="ignore")
BT_state = BT_state.stdout
注意我沒有運行上面的代碼,所以你可能需要稍微調整一下。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/482632.html
