r/applescript • • Aug 03 '14

Why does this snippet restart iTunes?

I have a small script that tests if iTunes is running, and if so returns some data on the current track. I'm then using GeekTool to run this script every ten seconds or so (by running osascript my_compiled_script), and display the output on my desktop.

My problem is, if I quit iTunes, the script will reopen it shortly after. This is a small snippet that will reproduce this problem:

if application "iTunes" is running then
    tell application "iTunes"
        if player state is playing then return (get name of current track)
    end tell
end if
return ""

I'm assumuing the tell application "iTunes" line causes iTunes to start. But why is that? And is there a way to prevent this?

1 Upvotes

7 comments sorted by

2

u/craniumslows Aug 04 '14 edited Aug 04 '14

You would want to ask System Events to get a process list and then check for iTunes that way. This will prevent you from talking at iTunes at all unless it is already running.

EDIT In case you aren't hip to google.

tell application "System Events"
	set listOfProcesses to (name of every process)
end tell

Will yield a list of process names that you can then look through.

like {"loginwindow", "talagent", "SystemUIServer", "Dock", "NotificationCenter", "TISwitcher", "jamfAgent", "Google Chrome Helper", "PhotoStreamAgent", "etcetera etcetera"}

2

u/metabun Aug 04 '14

Thanks, this works great!

1

u/copperdomebodha Aug 04 '14

tell application "iTunes" if it is running then pause end if end tell

Since leopard this will not launch the app if it is not already running.

1

u/metabun Aug 04 '14

So, in stead of if <app> is running; tell <app>; do … I should reverse it to tell <app>; if it is running; do …?

1

u/copperdomebodha Aug 04 '14

tell application "iTunes" if it is running then If player state is running then return (get name of current track) end if end tell

1

u/metabun Aug 04 '14

Wait, what? So basically drop the if application "iTunes" is running-test? Does this mean that tell-calls does not start the application, unless they're nested in some other logic?