The Workflow class for Alfred 2 and 3

The Workflow object is the main interface to this library.

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

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

Create new Workflow instance.

  • 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. This must be a dict that contains github_slug and version keys. github_slug is of the form username/repo and version must correspond to the tag of a release. The boolean prereleases key is optional and if True will override the magic argument preference. This is only recommended when the installed workflow is a pre-release. See Self-Updating for more information.
  • input_encoding (unicode) – encoding of command line arguments
  • 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 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.

x.__delattr__(‘name’) <==> del


default object formatter


x.__getattribute__(‘name’) <==>


helper for pickle


helper for pickle


x.__setattr__(‘name’, value) <==> = value

__sizeof__() → int

size of object in memory, in bytes

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.

  • 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/', 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).

Item instance

See the Script Filter Results and the XML Format section of the documentation for a detailed description of what the various parameters do and how they interact with one another.

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


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’s environmental variables minus the alfred_ prefix.

New in version 1.7.

The variables Alfred 2.4+ exports are:

Variable Description
alfred_preferences Path to Alfred.alfredpreferences (where your workflows and settings are stored).
alfred_preferences_localhash Machine-specific preferences are stored in Alfred.alfredpreferences/preferences/local/<hash> (see alfred_preferences above for the path to Alfred.alfredpreferences)
alfred_theme ID of selected theme
alfred_theme_background Background colour of selected theme in format rgba(r,g,b,a)
alfred_theme_subtext Show result subtext. 0 = Always, 1 = Alternative actions only, 2 = Selected result only, 3 = Never
alfred_version Alfred version number, e.g. '2.4'
alfred_version_build Alfred build number, e.g. 277
alfred_workflow_bundleid Bundle ID, e.g. net.deanishe.alfred-mailto
alfred_workflow_cache Path to workflow’s cache directory
alfred_workflow_data Path to workflow’s data directory
alfred_workflow_name Name of current workflow
alfred_workflow_uid UID of workflow
alfred_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 as Version object.


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.


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.

  • name – name of datastore
  • data – data to store. This may be any object supported by the 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)

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.

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

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


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.

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

True if data is less than max_age old, else False


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

Return full 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

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 Manual 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.

Delete workflow’s settings_path.


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

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

Return full 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
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.

  • 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.

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).

OS X, 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.

  • 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

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, a ValueError will be raised.

  • 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.

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:


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 startswith


  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 : Match if query is a substring

    of item search key (case-insensitive).

  8. MATCH_ALLCHARS : Matches if 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.


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.


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.


Convert non-ASCII characters to closest ASCII equivalent.

New in version 1.3.


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.

  • 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

account password

Return type:



dict of info.plist contents.


alias of Item


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

New in version 1.9.10.

Returns:Version instance or None

Return path to logfile.

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

Create and return a logger that logs to both console and a log file.

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

Returns:an initialised Logger
magic_arguments = None

Mapping of available magic arguments. The built-in magic arguments are registered by default. To add your own magic arguments (or override built-ins), add a key:value pair where the key is what the user should enter (prefixed with magic_prefix) and the value is a callable that will be called when the argument is entered. If you would like to display a message in Alfred, the function should return a unicode string.

By default, the magic arguments documented here are registered.

magic_prefix = None

The prefix for all magic arguments. Default is workflow:


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

Returns:workflow name
Return type:unicode

Open the workflow’s cachedir in Finder.


Open the workflow’s datadir in Finder.


Open help_url in default browser.


Open logfile in default app (usually


Open a Terminal window at workflow’s workflowdir.


Open the workflow’s workflowdir in Finder.


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.

Delete settings, cache and data


Call func to run your workflow.

Parameters:func – Callable to call with self (i.e. the Workflow instance) as first argument.

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.

  • 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

Print stored items to console/Alfred as XML.


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

Return a dictionary subclass that saves itself when changed.

See Settings in the User Manual 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

Path to settings file within workflow’s data directory.

Returns:path to settings.json file
Return type:unicode

Check for update and download and install new workflow file

New in version 1.9.

See Self-updating in the User Manual 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.

  • 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.

data in datastore or None


Retrieve data from data directory. Returns None if there are no data stored.

New in version 1.8.

Parameters:name – name of datastore

Whether an update is available.

New in version 1.9.

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

Returns:True if an update is available, else False

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

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

Returns:full path to workflow root directory
Return type:unicode

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
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.

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

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

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

Atomic file writer.

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

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.

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

Decorator that postpones SIGTERM until wrapped function is complete.

New in version 1.12.

Since 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.


This decorator is NOT thread-safe.

class workflow.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.

class workflow.workflow.PasswordNotFound

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

class 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).