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

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您运行
subprocess
以在睡眠前获取BT_STATE
,但您在睡眠后不会再次运行它,因此变量bt_state
未更新。实际上,您正在两次检查同一件事。我已经在下面重构了您的代码,以分开不同的作品,希望更容易看到发生了什么。
将BT状态逻辑放入单独的方法中意味着,如果您需要更改该逻辑,则只需要在一个地方更改它即可。
You run the
subprocess
to get theBT_state
before the sleep but you don't run it again after the sleep so the variableBT_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.
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.
睡觉10秒后,您不会刷新状态。尝试,
您甚至可以通过
当心我没有运行上面的代码来清理代码,因此您可能需要对其进行一些调整。
You're not refreshing the state after you sleep for 10 seconds. Try
You can probably even clean up your code by doing
Beware I didn't run the code above, so you may need to tweak it a little.