API documentation

Documentation for Alfred-Workflow’s classes and methods.

See User Guide for documentation focussed on performing specific tasks.

See the main index for a list of all classes and methods.

Workflow objects

The Workflow object is the main interface to this library.

Workflow is targeted at Alfred 2. Use Workflow3 if you want to use Alfred 3’s new features, such as workflow variables or more powerful modifiers.

See Workflow setup and skeleton in the User Guide for an example of how to set up your Python script to best utilise the Workflow object.

class workflow.Workflow(default_settings=None, update_settings=None, input_encoding=u'utf-8', normalization=u'NFC', capture_args=True, libraries=None, help_url=None)

The Workflow object is the main interface to Alfred-Workflow.

It provides APIs for accessing the Alfred/workflow environment, storing & caching data, using Keychain, and generating Script Filter feedback.

Workflow is compatible with both Alfred 2 and 3. The Workflow3 subclass provides additional, Alfred 3-only features, such as workflow variables.

Parameters:
  • default_settings (dict) – default workflow settings. If no settings file exists, Workflow.settings will be pre-populated with default_settings.
  • update_settings (dict) – settings for updating your workflow from GitHub releases. The only required key is github_slug, whose value must take the form of username/repo. If specified, Workflow will check the repo’s releases for updates. Your workflow must also have a semantic version number. Please see the User Manual and update API docs <api-updates> for more information.
  • input_encoding (unicode) – encoding of command line arguments. You should probably leave this as the default (utf-8), which is the encoding Alfred uses.
  • normalization (unicode) – normalisation to apply to CLI args. See Workflow.decode() for more details.
  • capture_args (Boolean) – Capture and act on workflow:* arguments. See Magic arguments for details.
  • libraries (tuple or list) – sequence of paths to directories containing libraries. These paths will be prepended to sys.path.
  • help_url (unicode or str) – URL to webpage where a user can ask for help with the workflow, report bugs, etc. This could be the GitHub repo or a page on AlfredForum.com. If your workflow throws an error, this URL will be displayed in the log and Alfred’s debugger. It can also be opened directly in a web browser with the workflow:help magic argument.
add_item(title, subtitle=u'', modifier_subtitles=None, arg=None, autocomplete=None, valid=False, uid=None, icon=None, icontype=None, type=None, largetext=None, copytext=None, quicklookurl=None)

Add an item to be output to Alfred.

Parameters:
  • title (unicode) – Title shown in Alfred
  • subtitle (unicode) – Subtitle shown in Alfred
  • modifier_subtitles (dict) – Subtitles shown when modifier (CMD, OPT etc.) is pressed. Use a dict with the lowercase keys cmd, ctrl, shift, alt and fn
  • arg (unicode) – Argument passed by Alfred as {query} when item is actioned
  • autocomplete (unicode) – Text expanded in Alfred when item is TABbed
  • valid (Boolean) – Whether or not item can be actioned
  • uid (unicode) – Used by Alfred to remember/sort items
  • icon (unicode) – Filename of icon to use
  • icontype (unicode) – Type of icon. Must be one of None , 'filetype' or 'fileicon'. Use 'filetype' when icon is a filetype such as 'public.folder'. Use 'fileicon' when you wish to use the icon of the file specified as icon, e.g. icon='/Applications/Safari.app', icontype='fileicon'. Leave as None if icon points to an actual icon file.
  • type (unicode) – Result type. Currently only 'file' is supported (by Alfred). This will tell Alfred to enable file actions for this item.
  • largetext (unicode) – Text to be displayed in Alfred’s large text box if user presses CMD+L on item.
  • copytext (unicode) – Text to be copied to pasteboard if user presses CMD+C on item.
  • quicklookurl (unicode) – URL to be displayed using Alfred’s Quick Look feature (tapping SHIFT or ⌘+Y on a result).
Returns:

Item instance

See System icons for a list of the supported system icons.

Note

Although this method returns an Item instance, you don’t need to hold onto it or worry about it. All generated Item instances are also collected internally and sent to Alfred when send_feedback() is called.

The generated Item is only returned in case you want to edit it or do something with it other than send it to Alfred.

alfred_env

Dict of Alfred’s environmental variables minus alfred_ prefix.

New in version 1.7.

The variables Alfred 2.4+ exports are:

Variable Description
debug Set to 1 if Alfred’s debugger is open, otherwise unset.
preferences Path to Alfred.alfredpreferences (where your workflows and settings are stored).
preferences_localhash Machine-specific preferences are stored in Alfred.alfredpreferences/preferences/local/<hash> (see preferences above for the path to Alfred.alfredpreferences)
theme ID of selected theme
theme_background Background colour of selected theme in format rgba(r,g,b,a)
theme_subtext Show result subtext. 0 = Always, 1 = Alternative actions only, 2 = Selected result only, 3 = Never
version Alfred version number, e.g. '2.4'
version_build Alfred build number, e.g. 277
workflow_bundleid Bundle ID, e.g. net.deanishe.alfred-mailto
workflow_cache Path to workflow’s cache directory
workflow_data Path to workflow’s data directory
workflow_name Name of current workflow
workflow_uid UID of workflow
workflow_version The version number specified in the workflow configuration sheet/info.plist

Note: all values are Unicode strings except version_build and theme_subtext, which are integers.

Returns:dict of Alfred’s environmental variables without the alfred_ prefix, e.g. preferences, workflow_data.
alfred_version

Alfred version as Version object.

args

Return command line args as normalised unicode.

Args are decoded and normalised via decode().

The encoding and normalisation are the input_encoding and normalization arguments passed to Workflow (UTF-8 and NFC are the defaults).

If Workflow is called with capture_args=True (the default), Workflow will look for certain workflow:* args and, if found, perform the corresponding actions and exit the workflow.

See Magic arguments for details.

bundleid

Workflow bundle ID from environmental vars or info.plist.

Returns:bundle ID
Return type:unicode
cache_data(name, data)

Save data to cache under name.

If data is None, the corresponding cache file will be deleted.

Parameters:
  • name – name of datastore
  • data – data to store. This may be any object supported by the cache serializer
cache_serializer

Name of default cache serializer.

New in version 1.8.

This serializer is used by cache_data() and cached_data()

See SerializerManager for details.

Returns:serializer name
Return type:unicode
cached_data(name, data_func=None, max_age=60)

Return cached data if younger than max_age seconds.

Retrieve data from cache or re-generate and re-cache data if stale/non-existant. If max_age is 0, return cached data no matter how old.

Parameters:
  • name – name of datastore
  • data_func (callable) – function to (re-)generate data.
  • max_age (int) – maximum age of cached data in seconds
Returns:

cached data, return value of data_func or None if data_func is not set

cached_data_age(name)

Return age in seconds of cache name or 0 if cache doesn’t exist.

Parameters:name (unicode) – name of datastore
Returns:age of datastore in seconds
Return type:int
cached_data_fresh(name, max_age)

Whether cache name is less than max_age seconds old.

Parameters:
  • name – name of datastore
  • max_age (int) – maximum age of data in seconds
Returns:

True if data is less than max_age old, else False

cachedir

Path to workflow’s cache directory.

The cache directory is a subdirectory of Alfred’s own cache directory in ~/Library/Caches. The full path is:

~/Library/Caches/com.runningwithcrayons.Alfred-X/Workflow Data/<bundle id>

Alfred-X may be Alfred-2 or Alfred-3.

Returns:full path to workflow’s cache directory
Return type:unicode
cachefile(filename)

Path to filename in workflow’s cache directory.

Return absolute path to filename within your workflow’s cache directory.

Parameters:filename (unicode) – basename of file
Returns:full path to file within cache directory
Return type:unicode
check_update(force=False)

Call update script if it’s time to check for a new release.

New in version 1.9.

The update script will be run in the background, so it won’t interfere in the execution of your workflow.

See Self-updating in the User Guide for detailed information on how to enable your workflow to update itself.

Parameters:force (Boolean) – Force update check
clear_cache(filter_func=<function <lambda>>)

Delete all files in workflow’s cachedir.

Parameters:filter_func (callable) – Callable to determine whether a file should be deleted or not. filter_func is called with the filename of each file in the data directory. If it returns True, the file will be deleted. By default, all files will be deleted.
clear_data(filter_func=<function <lambda>>)

Delete all files in workflow’s datadir.

Parameters:filter_func (callable) – Callable to determine whether a file should be deleted or not. filter_func is called with the filename of each file in the data directory. If it returns True, the file will be deleted. By default, all files will be deleted.
clear_settings()

Delete workflow’s settings_path.

data_serializer

Name of default data serializer.

New in version 1.8.

This serializer is used by store_data() and stored_data()

See SerializerManager for details.

Returns:serializer name
Return type:unicode
datadir

Path to workflow’s data directory.

The data directory is a subdirectory of Alfred’s own data directory in ~/Library/Application Support. The full path is:

~/Library/Application Support/Alfred 2/Workflow Data/<bundle id>

Returns:full path to workflow data directory
Return type:unicode
datafile(filename)

Path to filename in workflow’s data directory.

Return absolute path to filename within your workflow’s data directory.

Parameters:filename (unicode) – basename of file
Returns:full path to file within data directory
Return type:unicode
debugging

Whether Alfred’s debugger is open.

Returns:True if Alfred’s debugger is open.
Return type:bool
decode(text, encoding=None, normalization=None)

Return text as normalised unicode.

If encoding and/or normalization is None, the input_encoding``and ``normalization parameters passed to Workflow are used.

Parameters:
  • text (encoded or Unicode string. If text is already a Unicode string, it will only be normalised.) – string
  • encoding (unicode or None) – The text encoding to use to decode text to Unicode.
  • normalization (unicode or None) – The nomalisation form to apply to text.
Returns:

decoded and normalised unicode

Workflow uses “NFC” normalisation by default. This is the standard for Python and will work well with data from the web (via web or json).

macOS, on the other hand, uses “NFD” normalisation (nearly), so data coming from the system (e.g. via subprocess or os.listdir()/os.path) may not match. You should either normalise this data, too, or change the default normalisation used by Workflow.

delete_password(account, service=None)

Delete the password stored at service/account.

Raise PasswordNotFound if account is unknown.

Parameters:
  • account (unicode) – name of the account the password is for, e.g. “Pinboard”
  • service (unicode) – Name of the service. By default, this is the workflow’s bundle ID
dumbify_punctuation(text)

Convert non-ASCII punctuation to closest ASCII equivalent.

This method replaces “smart” quotes and n- or m-dashes with their workaday ASCII equivalents. This method is currently not used internally, but exists as a helper method for workflow authors.

Parameters:text (unicode) – text to convert
Returns:text with only ASCII punctuation
Return type:unicode
filter(query, items, key=<function <lambda>>, ascending=False, include_score=False, min_score=0, max_results=0, match_on=127, fold_diacritics=True)

Fuzzy search filter. Returns list of items that match query.

query is case-insensitive. Any item that does not contain the entirety of query is rejected.

If query is an empty string or contains only whitespace, all items will match.

Parameters:
  • query (unicode) – query to test items against
  • items (list or tuple) – iterable of items to test
  • key (callable) – function to get comparison key from items. Must return a unicode string. The default simply returns the item.
  • ascending (Boolean) – set to True to get worst matches first
  • include_score (Boolean) – Useful for debugging the scoring algorithm. If True, results will be a list of tuples (item, score, rule).
  • min_score (int) – If non-zero, ignore results with a score lower than this.
  • max_results (int) – If non-zero, prune results list to this length.
  • match_on (int) – Filter option flags. Bitwise-combined list of MATCH_* constants (see below).
  • fold_diacritics (Boolean) – Convert search keys to ASCII-only characters if query only contains ASCII characters.
Returns:

list of items matching query or list of (item, score, rule) tuples if include_score is True. rule is the MATCH_* rule that matched the item.

Return type:

list

Matching rules

By default, filter() uses all of the following flags (i.e. MATCH_ALL). The tests are always run in the given order:

  1. MATCH_STARTSWITH
    Item search key starts with query (case-insensitive).
  2. MATCH_CAPITALS
    The list of capital letters in item search key starts with query (query may be lower-case). E.g., of would match OmniFocus, gc would match Google Chrome.
  3. MATCH_ATOM
    Search key is split into “atoms” on non-word characters (.,-,’ etc.). Matches if query is one of these atoms (case-insensitive).
  4. MATCH_INITIALS_STARTSWITH
    Initials are the first characters of the above-described “atoms” (case-insensitive).
  5. MATCH_INITIALS_CONTAIN
    query is a substring of the above-described initials.
  6. MATCH_INITIALS
    Combination of (4) and (5).
  7. MATCH_SUBSTRING
    query is a substring of item search key (case-insensitive).
  8. MATCH_ALLCHARS
    All characters in query appear in item search key in the same order (case-insensitive).
  9. MATCH_ALL
    Combination of all the above.

MATCH_ALLCHARS is considerably slower than the other tests and provides much less accurate results.

Examples:

To ignore MATCH_ALLCHARS (tends to provide the worst matches and is expensive to run), use match_on=MATCH_ALL ^ MATCH_ALLCHARS.

To match only on capitals, use match_on=MATCH_CAPITALS.

To match only on startswith and substring, use match_on=MATCH_STARTSWITH | MATCH_SUBSTRING.

Diacritic folding

New in version 1.3.

If fold_diacritics is True (the default), and query contains only ASCII characters, non-ASCII characters in search keys will be converted to ASCII equivalents (e.g. ü -> u, ß -> ss, é -> e).

See ASCII_REPLACEMENTS for all replacements.

If query contains non-ASCII characters, search keys will not be altered.

first_run

Return True if it’s the first time this version has run.

New in version 1.9.10.

Raises a ValueError if version isn’t set.

fold_to_ascii(text)

Convert non-ASCII characters to closest ASCII equivalent.

New in version 1.3.

Note

This only works for a subset of European languages.

Parameters:text (unicode) – text to convert
Returns:text containing only ASCII characters
Return type:unicode
get_password(account, service=None)

Retrieve the password saved at service/account.

Raise PasswordNotFound exception if password doesn’t exist.

Parameters:
  • account (unicode) – name of the account the password is for, e.g. “Pinboard”
  • service (unicode) – Name of the service. By default, this is the workflow’s bundle ID
Returns:

account password

Return type:

unicode

info

dict of info.plist contents.

item_class

alias of Item

last_version_run

Return version of last version to run (or None).

New in version 1.9.10.

Returns:Version instance or None
logfile

Path to logfile.

Returns:path to logfile within workflow’s cache directory
Return type:unicode
logger

Logger that logs to both console and a log file.

If Alfred’s debugger is open, log level will be DEBUG, else it will be INFO.

Use open_log() to open the log file in Console.

Returns:an initialised Logger
name

Workflow name from Alfred’s environmental vars or info.plist.

Returns:workflow name
Return type:unicode
open_cachedir()

Open the workflow’s cachedir in Finder.

open_datadir()

Open the workflow’s datadir in Finder.

open_help()

Open help_url in default browser.

open_log()

Open logfile in default app (usually Console.app).

open_terminal()

Open a Terminal window at workflow’s workflowdir.

open_workflowdir()

Open the workflow’s workflowdir in Finder.

prereleases

Whether workflow should update to pre-release versions.

New in version 1.16.

Returns:True if pre-releases are enabled with the magic argument or the update_settings dict, else False.
reset()

Delete workflow settings, cache and data.

File settings and directories cache and data are deleted.

run(func, text_errors=False)

Call func to run your workflow.

Parameters:
  • func – Callable to call with self (i.e. the Workflow instance) as first argument.
  • text_errors (Boolean) – Emit error messages in plain text, not in Alfred’s XML/JSON feedback format. Use this when you’re not running Alfred-Workflow in a Script Filter and would like to pass the error message to, say, a notification.

func will be called with Workflow instance as first argument.

func should be the main entry point to your workflow.

Any exceptions raised will be logged and an error message will be output to Alfred.

save_password(account, password, service=None)

Save account credentials.

If the account exists, the old password will first be deleted (Keychain throws an error otherwise).

If something goes wrong, a KeychainError exception will be raised.

Parameters:
  • account (unicode) – name of the account the password is for, e.g. “Pinboard”
  • password (unicode) – the password to secure
  • service (unicode) – Name of the service. By default, this is the workflow’s bundle ID
send_feedback()

Print stored items to console/Alfred as XML.

set_last_version(version=None)

Set last_version_run to current version.

New in version 1.9.10.

Parameters:version (Version instance or unicode) – version to store (default is current version)
Returns:True if version is saved, else False
settings

Return a dictionary subclass that saves itself when changed.

See Settings in the User Guide for more information on how to use settings and important limitations on what it can do.

Returns:Settings instance initialised from the data in JSON file at settings_path or if that doesn’t exist, with the default_settings dict passed to Workflow on instantiation.
Return type:Settings instance
settings_path

Path to settings file within workflow’s data directory.

Returns:path to settings.json file
Return type:unicode
start_update()

Check for update and download and install new workflow file.

New in version 1.9.

See Self-updating in the User Guide for detailed information on how to enable your workflow to update itself.

Returns:True if an update is available and will be installed, else False
store_data(name, data, serializer=None)

Save data to data directory.

New in version 1.8.

If data is None, the datastore will be deleted.

Note that the datastore does NOT support mutliple threads.

Parameters:
  • name – name of datastore
  • data – object(s) to store. Note: some serializers can only handled certain types of data.
  • serializer – name of serializer to use. If no serializer is specified, the default will be used. See SerializerManager for more information.
Returns:

data in datastore or None

stored_data(name)

Retrieve data from data directory.

Returns None if there are no data stored under name.

New in version 1.8.

Parameters:name – name of datastore
update_available

Whether an update is available.

New in version 1.9.

See Self-updating in the User Guide for detailed information on how to enable your workflow to update itself.

Returns:True if an update is available, else False
version

Return the version of the workflow.

New in version 1.9.10.

Get the workflow version from environment variable, the update_settings dict passed on instantiation, the version file located in the workflow’s root directory or info.plist. Return None if none exists or ValueError if the version number is invalid (i.e. not semantic).

Returns:Version of the workflow (not Alfred-Workflow)
Return type:Version object
workflowdir

Path to workflow’s root directory (where info.plist is).

Returns:full path to workflow root directory
Return type:unicode
workflowfile(filename)

Return full path to filename in workflow’s root directory.

Parameters:filename (unicode) – basename of file
Returns:full path to file within data directory
Return type:unicode

Settings

Workflow and Workflow3 objects each have a settings attribute that provides a simple API for storing workflow settings.

class workflow.workflow.Settings(filepath, defaults=None)

A dictionary that saves itself when changed.

Dictionary keys & values will be saved as a JSON file at filepath. If the file does not exist, the dictionary (and settings file) will be initialised with defaults.

Parameters:
  • filepath (unicode) – where to save the settings
  • defaults (dict) – dict of default settings

An appropriate instance is provided by Workflow instances at Workflow.settings.

save(self)

Save settings to JSON file specified in self._filepath.

If you’re using this class via Workflow.settings, which you probably are, self._filepath will be settings.json in your workflow’s data directory (see datadir).

save

Save settings to JSON file specified in self._filepath.

If you’re using this class via Workflow.settings, which you probably are, self._filepath will be settings.json in your workflow’s data directory (see datadir).

setdefault(key, value=None)

Override dict method to save on update.

update(*args, **kwargs)

Override dict method to save on update.

Serializers

The serialization API provided by SerializerManager is used by Workflow to store saved & cached data and settings. You can register your own serializers on a manager.

The default manager (which supports JSON, pickle and cPickle) is at workflow.manager.

class workflow.workflow.SerializerManager

Contains registered serializers.

New in version 1.8.

A configured instance of this class is available at workflow.manager.

Use register() to register new (or replace existing) serializers, which you can specify by name when calling Workflow data storage methods.

See Serialization of stored/cached data and Persistent data for further information.

register(name, serializer)

Register serializer object under name.

Raises AttributeError if serializer in invalid.

Note

name will be used as the file extension of the saved files.

Parameters:
  • name (unicode or str) – Name to register serializer under
  • serializer – object with load() and dump() methods
serializer(name)

Return serializer object for name.

Parameters:name (unicode or str) – Name of serializer to return
Returns:serializer object or None if no such serializer is registered.
serializers

Return names of registered serializers.

unregister(name)

Remove registered serializer with name.

Raises a ValueError if there is no such registered serializer.

Parameters:name (unicode or str) – Name of serializer to remove
Returns:serializer object
class workflow.workflow.JSONSerializer

Wrapper around json. Sets indent and encoding.

New in version 1.8.

Use this serializer if you need readable data files. JSON doesn’t support Python objects as well as cPickle/pickle, so be careful which data you try to serialize as JSON.

classmethod dump(obj, file_obj)

Serialize object obj to open JSON file.

New in version 1.8.

Parameters:
  • obj (JSON-serializable data structure) – Python object to serialize
  • file_obj (file object) – file handle
classmethod load(file_obj)

Load serialized object from open JSON file.

New in version 1.8.

Parameters:file_obj (file object) – file handle
Returns:object loaded from JSON file
Return type:object
class workflow.workflow.CPickleSerializer

Wrapper around cPickle. Sets protocol.

New in version 1.8.

This is the default serializer and the best combination of speed and flexibility.

classmethod dump(obj, file_obj)

Serialize object obj to open pickle file.

New in version 1.8.

Parameters:
  • obj (Python object) – Python object to serialize
  • file_obj (file object) – file handle
classmethod load(file_obj)

Load serialized object from open pickle file.

New in version 1.8.

Parameters:file_obj (file object) – file handle
Returns:object loaded from pickle file
Return type:object
class workflow.workflow.PickleSerializer

Wrapper around pickle. Sets protocol.

New in version 1.8.

Use this serializer if you need to add custom pickling.

classmethod dump(obj, file_obj)

Serialize object obj to open pickle file.

New in version 1.8.

Parameters:
  • obj (Python object) – Python object to serialize
  • file_obj (file object) – file handle
classmethod load(file_obj)

Load serialized object from open pickle file.

New in version 1.8.

Parameters:file_obj (file object) – file handle
Returns:object loaded from pickle file
Return type:object

Exceptions

Alfred-Workflow defines the following exceptions, which may be raised by the Keychain API.

exception workflow.KeychainError

Raised for unknown Keychain errors.

Raised by methods Workflow.save_password(), Workflow.get_password() and Workflow.delete_password() when security CLI app returns an unknown error code.

exception workflow.PasswordNotFound

Password not in Keychain.

Raised by method Workflow.get_password() when account is unknown to the Keychain.

exception workflow.workflow.PasswordExists

Raised when trying to overwrite an existing account password.

You should never receive this error: it is used internally by the Workflow.save_password() method to know if it needs to delete the old password first (a Keychain implementation detail).

Workflow3 objects

New in version 1.18.

Workflow3 is an Alfred 3-only version of Workflow that supports Alfred 3’s new features.

It supports setting Workflow variables and the more advanced modifiers supported by Alfred 3.

In order for the feedback mechanism to work correctly, it’s important to create Item3 and Modifier objects via the add_item() and Item3.add_modifier() methods respectively. If you instantiate Item3 or Modifier objects directly, the current Workflow3 object won’t be aware of them, and they won’t be sent to Alfred when you call send_feedback().

class workflow.Workflow3(**kwargs)

Workflow class that generates Alfred 3 feedback.

It is a subclass of Workflow and most of its methods are documented there.

item_class

class – Class used to generate feedback items.

variables

dict – Top level workflow variables.

add_item(title, subtitle=u'', arg=None, autocomplete=None, valid=False, uid=None, icon=None, icontype=None, type=None, largetext=None, copytext=None, quicklookurl=None, match=None)

Add an item to be output to Alfred.

Parameters:match (unicode, optional) – If you have “Alfred filters results” turned on for your Script Filter, Alfred (version 3.5 and above) will filter against this field, not title.

See Workflow.add_item() for the main documentation and other parameters.

The key difference is that this method does not support the modifier_subtitles argument. Use the add_modifier() method instead on the returned item instead.

Returns:Alfred feedback item.
Return type:Item3
cache_data(name, data, session=False)

Cache API with session-scoped expiry.

New in version 1.25.

Parameters:
  • name (str) – Cache key
  • data (object) – Data to cache
  • session (bool, optional) – Whether to scope the cache to the current session.

name and data are the same as for the cache_data() method on Workflow.

If session is True, then name is prefixed with session_id.

cached_data(name, data_func=None, max_age=60, session=False)

Cache API with session-scoped expiry.

New in version 1.25.

Parameters:
  • name (str) – Cache key
  • data_func (callable) – Callable that returns fresh data. It is called if the cache has expired or doesn’t exist.
  • max_age (int) – Maximum allowable age of cache in seconds.
  • session (bool, optional) – Whether to scope the cache to the current session.

name, data_func and max_age are the same as for the cached_data() method on Workflow.

If session is True, then name is prefixed with session_id.

clear_session_cache(current=False)

Remove session data from the cache.

New in version 1.25.

Changed in version 1.27.

By default, data belonging to the current session won’t be deleted. Set current=True to also clear current session.

Parameters:current (bool, optional) – If True, also remove data for current session.
getvar(name, default=None)

Return value of workflow variable for name or default.

Parameters:
  • name (unicode) – Variable name.
  • default (None, optional) – Value to return if variable is unset.
Returns:

Value of variable if set or default.

Return type:

unicode or default

item_class

alias of Item3

obj

Feedback formatted for JSON serialization.

Returns:Data suitable for Alfred 3 feedback.
Return type:dict
rerun

How often (in seconds) Alfred should re-run the Script Filter.

send_feedback()

Print stored items to console/Alfred as JSON.

session_id

A unique session ID every time the user uses the workflow.

New in version 1.25.

The session ID persists while the user is using this workflow. It expires when the user runs a different workflow or closes Alfred.

setvar(name, value, persist=False)

Set a “global” workflow variable.

Changed in version 1.33.

These variables are always passed to downstream workflow objects.

If you have set rerun, these variables are also passed back to the script when Alfred runs it again.

Parameters:
  • name (unicode) – Name of variable.
  • value (unicode) – Value of variable.
  • persist (bool, optional) – Also save variable to info.plist?
warn_empty(title, subtitle=u'', icon=None)

Add a warning to feedback if there are no items.

New in version 1.31.

Add a “warning” item to Alfred feedback if no other items have been added. This is a handy shortcut to prevent Alfred from showing its fallback searches, which is does if no items are returned.

Parameters:
  • title (unicode) – Title of feedback item.
  • subtitle (unicode, optional) – Subtitle of feedback item.
  • icon (str, optional) – Icon for feedback item. If not specified, ICON_WARNING is used.
Returns:

Newly-created item.

Return type:

Item3

Workflow variables

New in version 1.18.

Alfred 3 allows you to pass around variables in your workflows. It passes these to your scripts as environment variables (access them with os.getenv()), and you can pass variables back to Alfred via JSON.

In Script Filters, use the setvar() methods on Workflow3, Item3 and Modifier.

In Run Script actions, use the Variables.

See Workflow variables in the User Guide for more information.

Item3 and Modifier are documented below, in the Advanced modifiers section.

class workflow.Variables(arg=None, **variables)

Workflow variables for Run Script actions.

This class allows you to set workflow variables from Run Script actions.

It is a subclass of dict.

>>> v = Variables(username='deanishe', password='hunter2')
>>> v.arg = u'output value'
>>> print(v)

See Setting variables from Run Script actions in the User Guide for more information.

Parameters:
  • arg (unicode, optional) – Main output/{query}.
  • **variables – Workflow variables to set.
arg

unicode – Output value ({query}).

config

dict – Configuration for downstream workflow element.

obj

Return alfredworkflow dict.

Advanced modifiers

New in version 1.18.

Changed in version 1.27.

You can specify alternate arg, subtitle and variables if a Script Filter result is actioned while holding down a modifier key.

As of Alfred-Workflow version 1.27 and Alfred version 3.4.1, you can also specify an alternative icon for a modifier.

Add a modifier to an item using Item3.add_modifier(), and configure the Modifier via its attributes and setvar() method.

class workflow.workflow3.Item3(title, subtitle=u'', arg=None, autocomplete=None, match=None, valid=False, uid=None, icon=None, icontype=None, type=None, largetext=None, copytext=None, quicklookurl=None)

Represents a feedback item for Alfred 3.

Generates Alfred-compliant JSON for a single item.

Don’t use this class directly (as it then won’t be associated with any Workflow3 object), but rather use Workflow3.add_item(). See add_item() for details of arguments.

add_modifier(key, subtitle=None, arg=None, valid=None, icon=None, icontype=None)

Add alternative values for a modifier key.

Parameters:
  • key (unicode) – Modifier key, e.g. "cmd" or "alt"
  • subtitle (unicode, optional) – Override item subtitle.
  • arg (unicode, optional) – Input for following action.
  • valid (bool, optional) – Override item validity.
  • icon (unicode, optional) – Filepath/UTI of icon.
  • icontype (unicode, optional) – Type of icon. See Workflow.add_item() for valid values.
Returns:

Configured Modifier.

Return type:

Modifier

getvar(name, default=None)

Return value of workflow variable for name or default.

Parameters:
  • name (unicode) – Variable name.
  • default (None, optional) – Value to return if variable is unset.
Returns:

Value of variable if set or default.

Return type:

unicode or default

obj

Item formatted for JSON serialization.

Returns:Data suitable for Alfred 3 feedback.
Return type:dict
setvar(name, value)

Set a workflow variable for this Item.

Parameters:
  • name (unicode) – Name of variable.
  • value (unicode) – Value of variable.
class workflow.workflow3.Modifier(key, subtitle=None, arg=None, valid=None, icon=None, icontype=None)

Modify Item3 arg/icon/variables when modifier key is pressed.

Don’t use this class directly (as it won’t be associated with any Item3), but rather use Item3.add_modifier() to add modifiers to results.

>>> it = wf.add_item('Title', 'Subtitle', valid=True)
>>> it.setvar('name', 'default')
>>> m = it.add_modifier('cmd')
>>> m.setvar('name', 'alternate')

See Workflow variables in the User Guide for more information and example usage.

Parameters:
  • key (unicode) – Modifier key, e.g. "cmd", "alt" etc.
  • subtitle (unicode, optional) – Override default subtitle.
  • arg (unicode, optional) – Argument to pass for this modifier.
  • valid (bool, optional) – Override item’s validity.
  • icon (unicode, optional) – Filepath/UTI of icon to use
  • icontype (unicode, optional) – Type of icon. See Workflow.add_item() for valid values.
arg

unicode – Arg to pass to following action.

config

dict – Configuration for a downstream element, such as a File Filter.

icon

unicode – Filepath/UTI of icon.

icontype

unicode – Type of icon. See Workflow.add_item() for valid values.

key

unicode – Modifier key (see above).

subtitle

unicode – Override item subtitle.

valid

bool – Override item validity.

variables

dict – Workflow variables set by this modifier.

getvar(name, default=None)

Return value of workflow variable for name or default.

Parameters:
  • name (unicode) – Variable name.
  • default (None, optional) – Value to return if variable is unset.
Returns:

Value of variable if set or default.

Return type:

unicode or default

obj

Modifier formatted for JSON serialization for Alfred 3.

Returns:Modifier for serializing to JSON.
Return type:dict
setvar(name, value)

Set a workflow variable for this Item.

Parameters:
  • name (unicode) – Name of variable.
  • value (unicode) – Value of variable.

Background processes

New in version 1.4.

As Alfred may try to run your workflow on every keypress, it’s a good idea to execute longer-running tasks (e.g. fetching data from the a webservice or application) in a background process.

This module provides an API to run commands in background processes. Combine with the caching API to work from cached data while you fetch fresh data in the background.

See the User Manual for more information and examples.

workflow.background.run_in_background(name, args, **kwargs)

Cache arguments then call this script again via subprocess.call().

Parameters:
Returns:

exit code of sub-process

Return type:

int

When you call this function, it caches its arguments and then calls background.py in a subprocess. The Python subprocess will load the cached arguments, fork into the background, and then run the command you specified.

This function will return as soon as the background.py subprocess has forked, returning the exit code of that process (i.e. not of the command you’re trying to run).

If that process fails, an error will be written to the log file.

If a process is already running under the same name, this function will return immediately and will not run the specified command.

workflow.background.is_running(name)

Test whether task name is currently running.

Parameters:name (unicode) – name of task
Returns:True if task with name name is running, else False
Return type:bool
workflow.background.kill(name, sig=15)

Send a signal to job name via os.kill().

New in version 1.29.

Parameters:
  • name (str) – Name of the job
  • sig (int, optional) – Signal to send (default: SIGTERM)
Returns:

False if job isn’t running, True if signal was sent.

Return type:

bool

HTTP requests

workflow.web provides a simple API for retrieving data from the Web modelled on the excellent requests library.

The purpose of workflow.web is to cover trivial cases at just 0.5% of the size of requests.

Danger

As workflow.web is based on Python 2’s standard HTTP libraries, there are two important problems with SSL connections.

Python versions older than 2.7.9 (i.e. pre-Yosemite) do not verify SSL certificates when establishing HTTPS connections.

As a result, you must not use this module for sensitive connections unless you’re certain it will only run on 2.7.9/Yosemite and later. If your workflow is Alfred 3-only, this requirement is met.

Secondly, versions of macOS older than High Sierra (10.13) have an extremely outdated version of OpenSSL, which is incompatible with many servers’ SSL configuration.

Consequently, workflow.web cannot connect to such servers. As this includes GitHub’s SSL configuration, the update mechanism only works on High Sierra and later.

workflow.web.get(url, params=None, headers=None, cookies=None, auth=None, timeout=60, allow_redirects=True, stream=False)

Initiate a GET request. Arguments as for request().

Returns:Response instance
workflow.web.post(url, params=None, data=None, headers=None, cookies=None, files=None, auth=None, timeout=60, allow_redirects=False, stream=False)

Initiate a POST request. Arguments as for request().

Returns:Response instance
workflow.web.request(method, url, params=None, data=None, headers=None, cookies=None, files=None, auth=None, timeout=60, allow_redirects=False, stream=False)

Initiate an HTTP(S) request. Returns Response object.

Parameters:
  • method (unicode) – ‘GET’ or ‘POST’
  • url (unicode) – URL to open
  • params (dict) – mapping of URL parameters
  • data (dict or str) – mapping of form data {'field_name': 'value'} or str
  • headers (dict) – HTTP headers
  • cookies (dict) – cookies to send to server
  • files (dict) – files to upload (see below).
  • auth (tuple) – username, password
  • timeout (int) – connection timeout limit in seconds
  • allow_redirects (bool) – follow redirections
  • stream (bool) – Stream content instead of fetching it all at once.
Returns:

Response object

Return type:

Response

The files argument is a dictionary:

{'fieldname' : { 'filename': 'blah.txt',
                 'content': '<binary data>',
                 'mimetype': 'text/plain'}
}
  • fieldname is the name of the field in the HTML form.
  • mimetype is optional. If not provided, mimetypes will be used to guess the mimetype, or application/octet-stream will be used.

Response objects

class workflow.web.Response(request, stream=False)

Returned by request() / get() / post() functions.

Simplified version of the Response object in the requests library.

>>> r = request('http://www.google.com')
>>> r.status_code
200
>>> r.encoding
ISO-8859-1
>>> r.content  # bytes
<html> ...
>>> r.text  # unicode, decoded according to charset in HTTP header/meta tag
u'<html> ...'
>>> r.json()  # content parsed as JSON
content

Raw content of response (i.e. bytes).

Returns:Body of HTTP response
Return type:str
encoding

Text encoding of document or None.

Returns:Text encoding if found.
Return type:str or None
iter_content(chunk_size=4096, decode_unicode=False)

Iterate over response data.

New in version 1.6.

Parameters:
  • chunk_size (int) – Number of bytes to read into memory
  • decode_unicode (bool) – Decode to Unicode using detected encoding
Returns:

iterator

json()

Decode response contents as JSON.

Returns:object decoded from JSON
Return type:list, dict or unicode
raise_for_status()

Raise stored error if one occurred.

error will be instance of urllib2.HTTPError

save_to_path(filepath)

Save retrieved data to file at filepath.

Parameters:filepath – Path to save retrieved data.
stream

Whether response is streamed.

Returns:True if response is streamed.
Return type:bool
text

Unicode-decoded content of response body.

If no encoding can be determined from HTTP headers or the content itself, the encoded response body will be returned instead.

Returns:Body of HTTP response
Return type:unicode or str

Workflow updates

New in version 1.9.

Add self-updating capabilities to your workflow. It regularly (every day by default) fetches the latest releases from the specified GitHub repository.

Currently, only updates from GitHub releases are supported.

Important

Alfred-Workflow will check for updates, but will neither install them nor notify the user that an update is available.

Normally, you would not use workflow.update directly, but use the corresponding methods on Workflow and Workflow3.

Please see Self-updating in the User Guide for information on how to enable automatic updates in your workflow.

workflow.update.check_update(github_slug, current_version, prereleases=False)

Check whether a newer release is available on GitHub.

Parameters:
  • github_slugusername/repo for workflow’s GitHub repo
  • current_version (unicode) – the currently installed version of the workflow. Semantic versioning is required.
  • prereleases – Whether to include pre-releases.
Returns:

True if an update is available, else False

If an update is available, its version number and download URL will be cached.

workflow.update.install_update()

If a newer release is available, download and install it.

Returns:True if an update is installed, else False

Helpers

class workflow.update.Version(vstr)

Mostly semantic versioning.

The main difference to proper semantic versioning is that this implementation doesn’t require a minor or patch version.

Version strings may also be prefixed with “v”, e.g.:

>>> v = Version('v1.1.1')
>>> v.tuple
(1, 1, 1, '')
>>> v = Version('2.0')
>>> v.tuple
(2, 0, 0, '')
>>> Version('3.1-beta').tuple
(3, 1, 0, 'beta')
>>> Version('1.0.1') > Version('0.0.1')
True
match_version()

Match version and pre-release/build information in version strings

tuple

Version number as a tuple of major, minor, patch, pre-release.

workflow.update.download_workflow(url)

Download workflow at url to a local temporary file.

Parameters:url – URL to .alfredworkflow file in GitHub repo
Returns:path to downloaded file

Notifications

New in version 1.15.

Note

Notifications aren’t available in version of macOS older than 10.8/Mountain Lion. Calling notify() on these systems will silently do nothing.

notify allows you to post notifications via macOS’s Notification Center at any time, not just at the end of your script. Furthermore, it uses your workflow’s icon, not Alfred’s.

The main API is a single function, notify().

It works by copying a simple application to your workflow’s data directory. It replaces the application’s icon with your workflow’s icon and then calls the application to post notifications.

workflow.notify.notify(title=u'', text=u'', sound=None)

Post notification via Notify.app helper.

Parameters:
  • title (str, optional) – Notification title.
  • text (str, optional) – Notification body text.
  • sound (str, optional) – Name of sound to play.
Raises:

ValueError – Raised if both title and text are empty.

Returns:

True if notification was posted, else False.

Return type:

bool

Helper functions

These internal helper functions may also be useful in your workflow.

workflow.notify.convert_image(inpath, outpath, size)

Convert an image file using sips.

Parameters:
  • inpath (str) – Path of source file.
  • outpath (str) – Path to destination file.
  • size (int) – Width and height of destination image in pixels.
Raises:

RuntimeError – Raised if sips exits with non-zero status.

workflow.notify.png_to_icns(png_path, icns_path)

Convert PNG file to ICNS using iconutil.

Create an iconset from the source PNG file. Generate PNG files in each size required by macOS, then call iconutil to turn them into a single ICNS file.

Parameters:
  • png_path (str) – Path to source PNG file.
  • icns_path (str) – Path to destination ICNS file.
Raises:

RuntimeError – Raised if iconutil or sips fail.

workflow.notify.validate_sound(sound)

Coerce sound to valid sound name.

Returns None for invalid sounds. Sound names can be found in System Preferences > Sound > Sound Effects.

Parameters:sound (str) – Name of system sound.
Returns:Proper name of sound or None.
Return type:str

Utilities & helpers

A collection of functions and classes for common workflow-related tasks, such as running AppleScript or JXA code, or calling an External Trigger.

workflow.util.utf8ify(s)

Ensure string is a bytestring.

New in version 1.31.

Returns str objects unchanced, encodes unicode objects to UTF-8, and calls str() on anything else.

Parameters:s (object) – A Python object
Returns:UTF-8 string or string representation of s.
Return type:str
workflow.util.applescriptify(s)

Escape string for insertion into an AppleScript string.

New in version 1.31.

Replaces " with “& quote &”. Use this function if you want

to insert a string into an AppleScript script:
>>> script = 'tell application "Alfred 3" to search "{}"'
>>> query = 'g "python" test'
>>> script.format(applescriptify(query))
'tell application "Alfred 3" to search "g " & quote & "python" & quote & "test"'
Parameters:s (unicode) – Unicode string to escape.
Returns:Escaped string
Return type:unicode
workflow.util.run_command(cmd, **kwargs)

Run a command and return the output.

New in version 1.31.

A thin wrapper around subprocess.check_output() that ensures all arguments are encoded to UTF-8 first.

Parameters:
  • cmd (list) – Command arguments to pass to check_output.
  • **kwargs – Keyword arguments to pass to check_output.
Returns:

Output returned by check_output.

Return type:

str

workflow.util.run_applescript(script, *args, **kwargs)

Execute an AppleScript script and return its output.

New in version 1.31.

Run AppleScript either by filepath or code. If script is a valid filepath, that script will be run, otherwise script is treated as code.

Parameters:
  • script (str, optional) – Filepath of script or code to run.
  • *args – Optional command-line arguments to pass to the script.
  • **kwargs – Pass lang to run a language other than AppleScript.
Returns:

Output of run command.

Return type:

str

workflow.util.run_jxa(script, *args)

Execute a JXA script and return its output.

New in version 1.31.

Wrapper around run_applescript() that passes lang=JavaScript.

Parameters:
  • script (str) – Filepath of script or code to run.
  • *args – Optional command-line arguments to pass to script.
Returns:

Output of script.

Return type:

str

workflow.util.run_trigger(name, bundleid=None, arg=None)

Call an Alfred External Trigger.

New in version 1.31.

If bundleid is not specified, reads the bundle ID of the current workflow from Alfred’s environment variables.

Parameters:
  • name (str) – Name of External Trigger to call.
  • bundleid (str, optional) – Bundle ID of workflow trigger belongs to.
  • arg (str, optional) – Argument to pass to trigger.
class workflow.util.AppInfo(name, path, bundleid)

Information about an installed application.

Returned by appinfo(). All attributes are Unicode.

name

Name of the application, e.g. u'Safari'.

path

Path to the application bundle, e.g. u'/Applications/Safari.app'.

bundleid

Application’s bundle ID, e.g. u'com.apple.Safari'.

workflow.util.appinfo(name)

Get information about an installed application.

New in version 1.31.

Parameters:name (str) – Name of application to look up.
Returns:AppInfo tuple or None if app isn’t found.
Return type:AppInfo

Configuration

Functions for manipulating the values of workflow variables in the workflow configuration sheet/info.plist.

workflow.util.set_config(name, value, bundleid=None, exportable=False)

Set a workflow variable in info.plist.

New in version 1.33.

Parameters:
  • name (str) – Name of variable to set.
  • value (str) – Value to set variable to.
  • bundleid (str, optional) – Bundle ID of workflow variable belongs to.
  • exportable (bool, optional) – Whether variable should be marked as exportable (Don’t Export checkbox).
workflow.util.unset_config(name, bundleid=None)

Delete a workflow variable from info.plist.

New in version 1.33.

Parameters:
  • name (str) – Name of variable to delete.
  • bundleid (str, optional) – Bundle ID of workflow variable belongs to.

Other helpers

These utility classes and functions are used internally by Alfred-Workflow, but may also be useful in your workflow.

class workflow.util.LockFile(protected_path, timeout=0.0, delay=0.05)

Context manager to protect filepaths with lockfiles.

New in version 1.13.

Creates a lockfile alongside protected_path. Other LockFile instances will refuse to lock the same path.

>>> path = '/path/to/file'
>>> with LockFile(path):
>>>     with open(path, 'wb') as fp:
>>>         fp.write(data)
Parameters:
  • protected_path (unicode) – File to protect with a lockfile
  • timeout (float, optional) – Raises an AcquisitionError if lock cannot be acquired within this number of seconds. If timeout is 0 (the default), wait forever.
  • delay (float, optional) – How often to check (in seconds) if lock has been released.
delay

float – How often to check (in seconds) whether the lock can be acquired.

lockfile

unicode – Path of the lockfile.

timeout

float – How long to wait to acquire the lock.

acquire(blocking=True)

Acquire the lock if possible.

If the lock is in use and blocking is False, return False.

Otherwise, check every delay seconds until it acquires lock or exceeds attr:timeout and raises an AcquisitionError.

locked

True if file is locked by this instance.

release()

Release the lock by deleting self.lockfile.

class workflow.util.uninterruptible(func, class_name='')

Decorator that postpones SIGTERM until wrapped function returns.

New in version 1.12.

Important

This decorator is NOT thread-safe.

As of version 2.7, Alfred allows Script Filters to be killed. If your workflow is killed in the middle of critical code (e.g. writing data to disk), this may corrupt your workflow’s data.

Use this decorator to wrap critical functions that must complete. If the script is killed while a wrapped function is executing, the SIGTERM will be caught and handled after your function has finished executing.

Alfred-Workflow uses this internally to ensure its settings, data and cache writes complete.

signal_handler(signum, frame)

Called when process receives SIGTERM.

workflow.util.atomic_writer(*args, **kwds)

Atomic file writer.

New in version 1.12.

Context manager that ensures the file is only written if the write succeeds. The data is first written to a temporary file.

Parameters:
  • fpath (unicode) – path of file to write to.
  • mode (string) – sames as for open()

Exceptions

The following exceptions, may be raised by utility functions.

exception workflow.util.AcquisitionError

Raised if a lock cannot be acquired.

exception subprocess.CalledProcessError(returncode, cmd, output=None)

This exception is raised when a process run by check_call() or check_output() returns a non-zero exit status. The exit status will be stored in the returncode attribute; check_output() will also store the output in the output attribute.