python-如果在if内

发布于 2025-01-31 03:38:44 字数 952 浏览 1 评论 0原文

我的脚本在第一个循环中寻找某些蓝牙状态标准(如果已打开,如果没有连接设备),然后睡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()

My script looks for certain bluetooth state criterias (if it's turned On and if there's no device connected) through the first loop and then sleeps 10 seconds to allow the user to change the bluetooth state and then checks again the same criterias before executing a prompt.

What I don't understand is that when I run the code and change the state before the wait period (10 seconds) end, it still runs the code inside the second if statement.

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()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

等风也等你 2025-02-07 03:38:44

您运行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状态逻辑放入单独的方法中意味着,如果您需要更改该逻辑,则只需要在一个地方更改它即可。

You run the subprocess to get the BT_state before the sleep but you don't run it again after the sleep so the variable BT_state is not updated. Effectively you are checking the same thing twice.

I have refactored your code below to separate out the different pieces in the hope that it is easier to see what is going on.

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()

Putting the BT state logic in a separate method means that if you need to change that logic, then you only need to change it in one place.

很酷又爱笑 2025-02-07 03:38:44

睡觉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

当心我没有运行上面的代码来清理代码,因此您可能需要对其进行一些调整。

You're not refreshing the state after you sleep for 10 seconds. Try

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)

You can probably even clean up your code by doing

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

Beware I didn't run the code above, so you may need to tweak it a little.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文