Check if display is sleeping in Applescript

2020-08-04 04:51发布

问题:

I'm trying to check if the display is sleeping, then execute some code in AppleScript.

So far I've tried this-

set display_sleep_state to do shell script "ioreg -n IODisplayWrangler |grep -i IOPowerManagement"
if display_sleep_state contains sleeping then
   -- Display is asleep
else if display_sleep_state contains awake then
   -- Display is awake
else
   -- We don't know.
end if

I found that here- https://superuser.com/questions/182018/determine-macs-screen-state-using-applescript

But display_sleep_state does not contain sleeping or awake.

I also tried this, which is pretty much the same except it sets the variables

delay 6 -- test with display awake, then test with display asleep (display sleep hotkeys are ctrl+shift+eject)
set sleeping to 1
set awake to 4
set display_sleep_state to do shell script "ioreg -n IODisplayWrangler |grep -i IOPowerManagement"
if display_sleep_state contains sleeping then
   say "display asleep"
else if display_sleep_state contains awake then
   say "display awake"
else

   say "unknown"
end if

source- http://macscripter.net/viewtopic.php?id=25003

But that also does not work and will switch between saying it's sleeping or awake randomly.

Anyone know how to do this?

回答1:

First of all, when you use a "do shell script" command the results are given back to you as text. Therefore your if statement must check for some text. As such your if statement should look like this... notice the quotes making the word sleeping into text.

if display_sleep_state contains "sleeping" then

Next, you need to know if "sleeping" is in the text returned from from the "do shell script" command. So run that command by itself and look at the text you get back. Look how the text changes when a display is awake versus sleeping and you'll find words you can use in your if statement to determine the display state. I don't have a sleeping display so I can't help you with that. Good luck.

do shell script "ioreg -n IODisplayWrangler |grep -i IOPowerManagement"


标签: applescript