Mac Script Check If App Running And Close It

Mac Script Check If App Running And Close It
class App

Right-click on the app and hover over Options in the menu. Apps that are set to open automatically will have a check mark next to Open at Login. Tap that option to uncheck it and disable it from.

  • Jun 12, 2019 Even if your Mac is brand-new, you'll still run into apps and programs that can slow it down from time to time. Quit all open apps. Don't just close the windows, but right-click on the app.
  • Apr 15, 2019 iTerm2, a popular Terminal replacement for macOS, will automatically close the window when a shell script exits. If you already use iTerm as your default terminal, you may have noticed that shell scripts launched from Finder still open with the stock Terminal app.
  • How to Quit apps/programs in Mac - latest macOS.

Completely revised - makes sense to read

Using class or instance methods¶

Generally you have the choice between using the class methods (e.g.App.open('application-identifier')) or first create an App instance and usethe instance methods afterwards (e.g. myApp=App('application-identifier')and then later on myApp.open()). There is no recomendation for a preferred usage, butif you plan to act on the same app or window more often,it might be more efficient, to use the instance approach.

For the string application-identifier principally the same rules apply, as if you would use the identifieron a command line. Especially if path specification contains blanks,it must be enclosed in double-quotes.

If the application name is given without a path specification, then it must be found on the system,according to the rules of that system (Windows: is on system path, Mac: is in an /Applications folder, …).

Examples:

How to create an App instance

The basic choice is to just say someApp=App('some-app-identifier') and youhave your app instance, that you can later use together with its methods,without having to specify the string again.

Generally all class methods return an app instance,that you might save in a variable to use it later in your script.

At time of instance creation the process list is scanned for the name of theexecutable using the given text. If this is found, the app instance is initialized with the respectiveinformation (PID, executable, window title of main/frontmost window).So you could directly ask the app instance, wether it is running (isRunning()),has a main window (hasWindow()), get the title of that main window (getWindow())and get the process id (PID) (getPID).

The string representation of an app instance looks like this:
[nPID:executableName(main/frontmostwindowtitle)]giventext

BE AWARE The application-identifier can no longer be (part of) a window title - it must specify an executable.If you want to reference a running application with (part of) a window title, you have to use App.focus().

NOTE Currently the information, wether a window is hidden or minimized, is not availableand it is not possible yet, to bring such a window to front with a compound SikuliX feature.

Mac script check if app running and close it is working

Open, close an application or focus on it

class App
classmethod App(application)

Usage:someApp=App(application)

Create an App instance, to later use with the instance methods (see above)

The string application must allow the system to locate the application in the system specific mannor.If this is not possible you might try the full path to an application’s executable.

Optionally you might add parameters, that will be given to the application at time of open.

There are 3 options:
  • put the application string in apostrophes and the rest following the second apostroph will be taken as parameter string
  • put `` – `` (space 2 hyphens! space) between the applications name or path (no apostrophes!) and the parameter string.
  • use setUsing() with an already existing application object (created before)
Parameters:application – The name of an application (case-insensitive) or the path to the executable and optionally parameters
Returns:an App object, that can be used with the instance methods
classmethod open(application)

Usage:App.open(application)

Open the specified application, if it is not yet opened and bring it to front

Parameters:application – the same as for App(application
Returns:an App object, that can be used with the instance methods

This method is functionally equivalent to openApp().

classmethod focus(title[, index])

Usage:App.focus(title[,index])

Switch the input focus to a running application having a front-most window with a matching title.

Parameters:
  • title – The name of an application (case-insensitive) or (part of) a window title (case-sensitive).
  • index – optional number (counting from 0) telling which one you want to have in the row of possible matches.
Returns:

an App object, that can be used with the instance methods

If no index is given, it is taken as 0. If the index is not applicable (not enough matches)the returned App object is invalid and not useable.

So you might loop through possible matches by counting the index up from 0 until you get an invalid

Running

If you specify the exact window title of an open window, you will get exactlythis one. But if you specify some text, that is found in more than one openwindow title, you will get the first in the row of all these windows.So if you want exactly one specific window, you eitherneed to know the exact window title or at least some part of the title text,that makes this window unique in the current context (e.g. save a document witha specific name, before accessing it’s window).

macOS and Linux not yet possible, to identify a running app by part of the title of it’s frontmost window.If you want to use a window title to match the application, use App.focus() before,to get a valid App object.

This method is functionally equivalent to switchApp().

Check
classmethod close(application)

Usage:App.close(application)

It closes the running application matching the given string. It does nothingif no running application matches. If you want to use a window title to match the application, use App.focus() before,to get a valid App object.

Parameters:application – The name of an application (case-insensitive)

This method is functionally equivalent to closeApp().

setUsing(parametertext)

Usage:appName=someApp.setUsing('parm1xparm2yparm3z')where App instance someApp was created before.

Parameters:parametertext – a string, that is given to the application at startup (when using open() ) as if you would start the app from a commandline.
setWorkDir([workingFolder])
WINDOWS ONLY

Usage:appName=someApp.setWorkDir('pathtotheworkingdirectory')where App instance someApp was created before.

param workingFolder:
the absolute path, which gets the working directory. The location of the app exec-file is used if omitted.
open([waitTime])

Usage:someApp.open()where App instance someApp was created before.

Open this application.

Parameters:waitTime – optional: seconds as integer, that should be waited for the app to get running
Returns:the app instance, which will be invalid, if open failed.
focus()

Usage:someApp.focus() where App instance someApp was created before.

Switch the input focus to this application.

Returns:the app instance, which will be invalid, if open failed.
close([waitTime])

Usage:someApp.close() where App instance someApp was created before.

Close this application.

Parameters:waitTime – optional: seconds as integer, that should be waited for the app to no longer being running
Returns:the app instance, which should be invalid (not running) afterwards.
closeByKey([waitTime])

Usage:someApp.closeByKey() where App instance someApp was created before.

Close this application by bringing it to front first (focus()) an then issue the systemspecifickeybord shortcut to close an application. This might help in situations where the normal close() leads tooddities at a later restart of the application.

Parameters:waitTime – optional: seconds as integer, that should be waited for the app to no longer being running

Getting information about a running application

isValid()

Usage:ifnotsomeApp.isValid():someApp.open()where App instance someApp was created before.

Returns:True if the app has a process ID, False otherwise

Be aware This simply checks wether the app object has a valid process ID. Hence it returns instantly. But thereis no guarantee, that the app is still running. If you want to be sure, you have to use isRunning(0), whichevaluates the state of the app, but might take some 100 millisecs, depending on your system’s state.

isRunning([waitTime])

Usage:ifnotsomeApp.isRunning():someApp.open() where App instance someApp was created before.

Parameters:waitTime – optional: seconds as integer, that should be waited for the app to get running
Returns:True if the app is running (has a process ID), False otherwise

Be aware Until the wait time is elapsed, the state of the application is checked every second.If you use just isRunning(), the state check is done twice, waiting 1 second in between.Hence this might take up to 2 seconds.If you want, that only one check is done, use isRunning(0).

hasWindow()

Usage:ifnotsomeApp.hasWindow():openNewWindow()#someprivatefunctionwhere App instance someApp was created before.

Returns:True if the app is running and has a main window registered, False otherwise
getTitle()

Usage:title=someApp.getTitle()where App instance someApp was created before.

Returns:the title of the frontmost window of this application, might be an empty string
getPID()

Usage:pid=someApp.getPID()where App instance someApp was created before.

Returns:the process ID as number if app is running, -1 otherwise
getName()

Usage:appName=someApp.getName()where App instance someApp was created before.

Returns:the short name of the app as it is shown in the process list
classmethod pause(waitTime)
Running

Usage:App.pause(someTime) (convenience function)

Just do nothing for the given amount of time in seconds (integer or float).

Dealing with Application windows¶

classmethod focusedWindow()

Usage:App.focusedWindow()

Identify the currently focused or the frontmost window and switch to it.Sikuli does not tell you, to which application this window belongs.

Returns:a Region object representing the window or None ifthere is no such window.

On Mac, when starting a script, Sikuli hides its window and startsprocessing the script. In this moment, no window has focus. Thus, it isnecessary to first click somewhere or use App.focus() to focus on awindow. In this case, this method may return None.

On Windows, this method always returns a region. When there is no windowopened on the desktop, the region may refer to a special window such as thetask bar or an icon in the system tray.

Example:

window([n])

Usage 1:App(application).window([n]) an App instance is created on the fly.

Usage 2:someApp.window([n]) where App instance someApp was created before.

Get the region corresponding to the n-th window of this application (Mac) ora series of windows with the matching title (Windows/Linux).

Parameters:n – 0 or a positive integer number. If ommitted, 0 is taken asdefault.
Returns:the region on the screen occupied by the window, if such windowexists and None if otherwise.

Below is an example that tries to open a Firefox browser window and switchesto the address field (Windows):

Afterwards, it focuses on the Firefox application, uses the window() method toobtain the region of the frontmost window, applies some operationswithin the region, and finally closes the window:

Below is another example that highlights all the windows of anapplication by looping through them (Mac):

getTitle([n])

Usage: see App.window([n])

Returns:the title of the frontmost/nth window of this application, might be an empty string

General aspects, hints and tipps¶

  • Be aware, that especially the window handling feature is experimentaland under further development.
  • Especially on Windows be aware, that there might be many matchingwindows and windows, that might not be visible at all. Currently thewindow() function has no feature to identify a special window besidesreturning the region. So you might need some additional checks to besure you are acting on the right window.
  • Windows/Linux: The close() function currently kills the application,without closing it’s windows before. This is an abnormal termination andmight be recognized by your application at the next start (e.g. Firefoxusually tries to reload the pages).
  • Even if the windows are hidden/minimized, their region that they have inthe visible state is returned. Currently there is no Sikuli feature, todecide wether the given window(n) is visible or not or if it iscurrently the frontmost window. The only guarentee: window()/window(0)is the topmost window of an application (Mac) or a series of matchingwindows (Windows/Linux).
  • Currently there are no methods available to act on such a window(resize, bring to front, get the window title, …).

Some tips:

  • Check the position of a window’s returned region: some apps hide therewindows by giving them “outside” coordinates (e.g. negative)
  • Check the size of a window’s returned region: normally your app windowswill occupy major parts of the screen, so a window’s returned region ofe.g. 150x30 might be some invisible stuff or an overlay on the real appwindow (e.g. the “search in history” input field on the Safari Top-Sitespage, which is reported as windows(0))
  • If you have more than one application window, try to position them atdifferent coordinates, so you can decide which one you act on in themoment.
  • It is sometimes possible to use the OCR text extraction featureRegion.text() to obtain the window title.

Some technical information on the implementation¶

The following information on how the features are implemented might help to understand problematic situations orto make suggestions on enhancements.

Windows

  • Applications are opened by internally running an appropriate startcommand.
  • The state of an application is evaluated by using the appropriate output of a tasklistcommand.
  • focus() and the windowrelated features are still implemented at the native level (WinUtil.dll). Same goesfor finding an application by part of its frontmost window’s title.

Mac

  • Applications are opened by internally running an appropriate opencommand.
  • The state of an application is evaluated by using the output of an appropriate AppleScript snippet, internally runusing macOS’s osascriptcommand.
  • focus() and the windowrelated features are still implemented at the native level (MacUtil.dll).

Linux

Mac Script Check If App Running And Close It Is Safe

The features are implemented by either running an appropriate shell command or by using appropriate features ofthe packages xdotool and wmctrl, which must be provided by the user.

Calling Command-Line Tools

In AppleScript, the do shell script command is used to execute command-line tools. This command is implemented by the Standard Additions scripting addition included with OS X.

Note

The Terminal app in /Applications/Utilities/ is scriptable and provides another way to execute command-line tools from scripts.

Executing Commands

The direct parameter of the do shell script command is a string containing the shell code you want to execute, as demonstrated in Listing 39-1, which simply lists a directory.

APPLESCRIPT

Listing 39-1AppleScript: Executing a simple shell command that lists the contents of a directory
  1. do shell script 'ls /Applications/'
  2. (*
  3. --> Result:
  4. 'App Store.app
  5. Automator.app
  6. Calculator.app
  7. Calendar.app
  8. ...'
  9. *)

Since the direct parameter of do shell script is a string, you can concatenate it with other strings at run time. Listing 39-2, for example, concatenates a shell command to a previously defined parameter value.

APPLESCRIPT

Listing 39-2AppleScript: Concatenating a command with a value
  1. set theHostName to 'www.apple.com'
  2. do shell script 'ping -c1 ' & theHostName

Quoting Strings

The shell uses space characters to separate parameters and gives special meaning to certain punctuation marks, such as $, (, ), and *. To ensure that strings are treated as expected—for example, spaces aren’t seen as delimiters—it’s best to wrap strings in quotes. This process is known as quoting. If your string contains quotes, they must also be escaped (preceded by a / character) so they are interpreted as part of the string. Listing 39-3 shows an example of an error occurring as a result of a parameter that contains a space.

APPLESCRIPT

Listing 39-3AppleScript: An error resulting from a string containing a space
  1. set thePath to '/Library/Application Support/'
  2. do shell script 'ls ' & thePath
  3. --> Result: error 'ls: /Library/Application: No such file or directoryrls: Support: No such file or directory' number 1

The easiest way to quote a string is to use the quoted form property of the text class, as demonstrated in Listing 39-4. This property returns the string in a form that’s safe from further interpretation by the shell, regardless of its contents.

APPLESCRIPT

Listing 39-4AppleScript: Quoting a string to prevent errors

Mac Script Check If App Running And Close It Is Going

  1. set thePath to quoted form of '/Library/Application Support/'
  2. --> Result: '/Library/Application Support/'
  3. do shell script 'ls ' & thePath
  4. (*
  5. --> Result:
  6. 'App Store
  7. Apple
  8. ...
  9. '
  10. *)

More Information

For more information about the do shell script command, see Commands Reference in AppleScript Language Guide and Technical Note TN2065.

Mac Script Check If App Running And Close It Is Fake

Copyright © 2018 Apple Inc. All rights reserved. Terms of Use | Privacy Policy | Updated: 2016-06-13