How to check in AppleScript if an app is running, without launching it - via osascript utility

后端 未结 6 704
眼角桃花
眼角桃花 2020-11-30 20:11

Consider the following AppleScript:

on is_running(appName)
    tell application \"System Events\" to (name of processes) contains appName
end is_running

set         


        
6条回答
  •  死守一世寂寞
    2020-11-30 20:27

    I had the same problem as described here trying to set up an AppleScript (triggered by a BetterTouchTool gesture) that plays/pauses VLC or iTunes, but only iTunes if VLC is not running (due to my workflow) and, naturally, only VLC while it's running. (I use the automatic pause/play trigger for iTunes in VLC's settings, for launch and quit of the app.)

    VLC was always launched on the first use of the BetterTouchTool-trigger after every relaunch of BTT as the dictionary-cache is deleted at that point and the AppleScript handler has to launch every scripted application if a tell is aimed at it in order to call its dictionary.

    I didn't find anything that avoided this anywhere; there were some attempts, but none worked for me as the dictionary-call by the script handler is nothing we can influence. I came up with this dirty workaround:

    • Create a separate AppleScript file only containing the line that includes the tell for VLC
    • Save it at some place where it won't annoy you
    • Replace the line containing the tell in the original AppleScript with a line that runs that script

    This will lead to the first compilation of the script not calling the application (VLC, in my case) directly, only the script, which means that the application will not need to launch.

    VLC will need to launch once that separate file is called, but, well, if you call that file in order to tell VLC something, you will have VLC already opened (or will want it open) anyway.

    The AppleScript I call through my BetterTouchTool-trigger (a specific tap on the trackpad, in my case) looks like this:

    if application "iTunes" is running and not application "VLC" is running then
    tell application "iTunes" to playpause
    

    end if if application "VLC" is running then run script "/Users/jannis/bin/PlayVLC.scpt" end if

    The separate AppleScript file ("PLayVLC.scpt, saved in a folder called "bin" in my user folder which I created manually ages ago for such purposes) is just this:

    tell application "VLC" to play
    

    If you open that script manually, it will of course also launch VLC. But that hopefully won't be necessary often, or ever.

    I actually have no idea if this creates any deeper problems I don't know of as I'm not a pro coder; if so, please notify me. I hope this helps anyone!

提交回复
热议问题