API documentation

Documentation for Alfred-PyWorkflow’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

New in version 1.18.

The Workflow object is the main interface to this library.

Workflow is targeted at Alfred 4+. Use Workflow if such as workflow variables or 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='utf-8', normalization='NFC', capture_args=True, libraries=None, help_url=None)

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

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

Workflow is compatible with Alfred 3+.

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 (str) – encoding of command line arguments. You should probably leave this as the default (utf-8), which is the encoding Alfred uses.

  • normalization (str) – normalization 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 (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.

item_class

Class used to generate feedback items.

Type:

class

variables

Top level workflow variables.

Type:

dict

add_item(title, subtitle='', 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:
  • title (str) – Title shown in Alfred

  • subtitle (str) – Subtitle shown in Alfred

  • arg (str, list or tuple) – Argument passed by Alfred as {query} when item is actioned

  • autocomplete (str) – Text expanded in Alfred when item is TABbed

  • valid (Boolean) – Whether or not item can be actioned

  • uid (str) – Used by Alfred to remember/sort items

  • icon (str) – Filename of icon to use

  • icontype (str) – 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 (str) – Result type. Currently only 'file' is supported (by Alfred). This will tell Alfred to enable file actions for this item.

  • largetext (str) – Text to be displayed in Alfred’s large text box if user presses CMD+L on item.

  • copytext (str) – Text to be copied to pasteboard if user presses CMD+C on item.

  • quicklookurl (str) – URL to be displayed using Alfred’s Quick Look feature (tapping SHIFT or ⌘+Y on a result).

param match: 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 (optional).

Returns:

Alfred feedback Item instance

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

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

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. E.g. use the add_modifier() method to shown subtitles when modifier (CMD, OPT etc.) is pressed.

property alfred_env

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

property alfred_version

Alfred version as Version object.

property args

Return command line args as normalised unicode.

Args are decoded and normalised via decode().

The encoding and normalization 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.

property bundleid

Workflow bundle ID from environmental vars or info.plist.

Returns:

bundle ID

Return type:

str

cache_data(name, data, session=False)

Cache API with session-scoped expiry.

New in version 1.25.

Save data to cache under name. If data is None, the corresponding cache file will be deleted.

Parameters:
  • name (str) – name of datastore

  • data (object) – Data to store. This may be any object supported by the cache serializer

param session: Whether to scope the cache to the

current session (optional).

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

property 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:

str

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

Cache API with session-scoped expiry.

New in version 1.25.

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 (str) – Name of datastore

  • 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 cached data in seconds.

  • session (bool) – Whether to scope the cache to the current session (optional).

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 (str) – 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

property 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 in Alfred 4+:

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

Returns:

full path to workflow’s cache directory

Return type:

str

cachefile(filename)

Path to filename in workflow’s cache directory.

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

Parameters:

filename (str) – basename of file

Returns:

full path to file within cache directory

Return type:

str

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

clear_settings()

Delete workflow’s settings_path.

property 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:

str

property 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 for Alfred 4+ is:

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

Returns:

full path to workflow data directory

Return type:

str

datafile(filename)

Path to filename in workflow’s data directory.

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

Parameters:

filename (str) – basename of file

Returns:

full path to file within data directory

Return type:

str

property 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 (str or None) – The text encoding to use to decode text to Unicode.

  • normalization (str or None) – The nomalisation form to apply to text.

Returns:

decoded and normalised str

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 (str) – name of the account the password is for, e.g. “Pinboard”

  • service (str) – 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 (str) – text to convert

Returns:

text with only ASCII punctuation

Return type:

str

filter(query, items, key=<function Workflow.<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 (str) – 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 str 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.

property 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 (str) – text to convert

Returns:

text containing only ASCII characters

Return type:

str

get_password(account, service=None)

Retrieve the password saved at service/account.

Raise PasswordNotFound exception if password doesn’t exist.

Parameters:
  • account (str) – name of the account the password is for, e.g. “Pinboard”

  • service (str) – Name of the service. By default, this is the workflow’s bundle ID

Returns:

account password

Return type:

str

getvar(name, default=None)

Return value of workflow variable for name or default.

Parameters:
  • name (str) – Variable name.

  • default (None, optional) – Value to return if variable is unset.

Returns:

Value of variable if set or default.

Return type:

str or default

property info

dict of info.plist contents.

item_class

alias of Item

property last_version_run

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

New in version 1.9.10.

Returns:

Version instance or None

property logfile

Path to logfile.

Returns:

path to logfile within workflow’s cache directory

Return type:

str

property 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

magic_arguments

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

By default, the magic arguments documented here are registered.

magic_prefix

Prefix for all magic arguments. The default value is workflow: so keyword config would match user query workflow:config.

property name

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

Returns:

workflow name

Return type:

str

property obj

Feedback formatted for JSON serialization.

Returns:

Data suitable for Alfred 3 feedback.

Return type:

dict

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.

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

property rerun

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

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-PyWorkflow 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 (str) – name of the account the password is for, e.g. “Pinboard”

  • password (str) – the password to secure

  • service (str) – Name of the service. By default, this is the workflow’s bundle ID

send_feedback()

Print stored items to console/Alfred as JSON.

property session_id

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

set_last_version(version=None)

Set last_version_run to current version.

New in version 1.9.10.

Parameters:

version (Version instance or str) – version to store (default is current version)

Returns:

True if version is saved, else False

property 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

property settings_path

Path to settings file within workflow’s data directory.

Returns:

path to settings.json file

Return type:

str

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 (str) – Name of variable.

  • value (str) – Value of variable.

  • persist (bool, optional) – Also save variable to info.plist?

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

property 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

property 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-PyWorkflow)

Return type:

Version object

warn_empty(title, subtitle='', 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 (str) – Title of feedback item.

  • subtitle (str, 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:

Item

property workflowdir

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

Returns:

full path to workflow root directory

Return type:

str

workflowfile(filename)

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

Parameters:

filename (str) – basename of file

Returns:

full path to file within data directory

Return type:

str

Settings

Workflow 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 (str) – 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 and pickle) 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 (str) – Name to register serializer under

  • serializer – object with load() and dump() methods

serializer(name)

Return serializer object for name.

Parameters:

name (str or bytes) – Name of serializer to return

Returns:

serializer object or None if no such serializer is registered.

property 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 (str or bytes) – 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 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.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-PyWorkflow 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).

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 (str) – name of task

Returns:

True if task with name name is running, else False

Return type:

bool

workflow.background.kill(name, sig=Signals.SIGTERM)

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 (str) – ‘GET’ or ‘POST’

  • url (str) – 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  # str, decoded according to charset in HTTP header/meta tag
'<html> ...'
>>> r.json()  # content parsed as JSON
property content

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

Returns:

Body of HTTP response

Return type:

str

property 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 str

raise_for_status()

Raise stored error if one occurred.

error will be instance of urllib.error.HTTPError

save_to_path(filepath)

Save retrieved data to file at filepath.

Parameters:

filepath – Path to save retrieved data.

property stream

Whether response is streamed.

Returns:

True if response is streamed.

Return type:

bool

property 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:

str or byte

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

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

workflow.update.check_update(repo, current_version, prereleases=False, alfred_version=None)

Check whether a newer release is available on GitHub.

Parameters:
  • repo (str) – username/repo for workflow’s GitHub repo

  • current_version (str) – the currently installed version of the workflow. Semantic versioning is required.

  • prereleases (bool) – Whether to include pre-releases.

  • alfred_version (str) – version of currently-running Alfred. if empty, defaults to $alfred_version environment variable.

Returns:

True if an update is available, else False

Return type:

bool

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.Download(url, filename, version, prerelease=False)

A workflow file that is available for download.

url

URL of workflow file.

Type:

str

filename

Filename of workflow file.

Type:

str

version

Semantic version of workflow.

Type:

Version

prerelease

Whether version is a pre-release.

Type:

bool

alfred_version

Minimum compatible version of Alfred.

Type:

Version

property alfred_version

Minimum Alfred version based on filename extension.

property dict

Convert Download to dict.

classmethod from_dict(d)

Create a Download from a dict.

classmethod from_releases(js)

Extract downloads from GitHub releases.

Searches releases with semantic tags for assets with file extension .alfredworkflow or .alfredXworkflow where X is a number.

Files are returned sorted by latest version first. Any releases containing multiple files with the same (workflow) extension are rejected as ambiguous.

Parameters:

js (str) – JSON response from GitHub’s releases endpoint.

Returns:

Sequence of Download.

Return type:

list

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(pos=0, endpos=9223372036854775807)

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

property tuple

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

workflow.update.retrieve_download(dl)

Saves a download to a temporary file and returns path.

Parameters:

url (str) – URL to .alfredworkflow file in GitHub repo

Returns:

path to downloaded file

Return type:

str

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='', subtitle='', message='', sound=None)

Post notification via notificator helper app from Vítor Galvão.

Parameters:
  • title (str, optional) – Notification title.

  • subtitle (str, optional) – Notification title.

  • message (str) – 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

Utility & helper functions

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

Scripting

Functions to simplify running scripts, programs and applications.

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:
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. Any other keyword arguments are passed to run_command().

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, the bundle ID of the calling workflow is used.

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

name

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

path

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

bundleid

Application’s bundle ID, e.g. '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

Text

Text encoding and formatting.

workflow.util.unicodify(s, encoding='utf-8', norm=None)

Ensure string is Unicode.

New in version 1.31.

Decode encoded strings using encoding and normalise Unicode to form norm if specified.

Parameters:
  • s (str) – String to decode. May also be Unicode.

  • encoding (str, optional) – Encoding to use on bytestrings.

  • norm (None, optional) – Normalisation form to apply to Unicode string.

Returns:

Decoded, optionally normalised, Unicode string.

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:

>>> applescriptify('g "python" test')
'g " & quote & "python" & quote & "test'
Parameters:

s (str) – Unicode string to escape.

Returns:

Escaped string.

Return type:

str

Alfred’s API

Alfred-PyWorkflow provides functions that enable you to call Alfred’s AppleScript API directly from Python.

Workflow stuff

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

If bundleid is not specified, the bundle ID of the calling workflow is used.

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.

If bundleid is not specified, the bundle ID of the calling workflow is used.

Parameters:
  • name (str) – Name of variable to delete.

  • bundleid (str, optional) – Bundle ID of workflow variable belongs to.

Tell Alfred to reload a workflow from disk if it has changed. Normally, Alfred will notice when a workflow changes, but it won’t if the workflow’s directory is a symlink.

workflow.util.reload_workflow(bundleid=None)

Tell Alfred to reload a workflow from disk.

New in version 1.39.0.

If bundleid is not specified, the bundle ID of the calling workflow is used.

Parameters:

bundleid (str, optional) – Bundle ID of workflow to reload.

Alfred stuff

You can open Alfred in normal or file navigation mode:

workflow.util.search_in_alfred(query=None)

Open Alfred with given search query.

New in version 1.39.0.

Omit query to simply open Alfred’s main window.

Parameters:

query (str, optional) – Search query.

workflow.util.browse_in_alfred(path)

Open Alfred’s filesystem navigation mode at path.

New in version 1.39.0.

Parameters:

path (str) – File or directory path.

Or tell Alfred to action one or more files/directories:

workflow.util.action_in_alfred(paths)

Action the give filepaths in Alfred.

New in version 1.39.0.

Parameters:

paths (list) – Unicode paths to files/directories to action.

Finally, you can tell Alfred to use a specific theme:

workflow.util.set_theme(theme_name)

Change Alfred’s theme.

New in version 1.39.0.

Parameters:

theme_name (str) – Name of theme Alfred should use.

Miscellaneous

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

Writing files

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 (str) – 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

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

Type:

float

lockfile

Path of the lockfile.

Type:

str

timeout

How long to wait to acquire the lock.

Type:

float

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.

property 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-PyWorkflow 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(fpath, mode)

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 (str) – path of file to write to.

  • mode (string) – sames as for open()

Images & sounds

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 or located at /System/Library/Sounds.

Parameters:

sound (str) – Name of system sound.

Returns:

Proper name of sound or None.

Return type:

str

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, stderr=None)

Raised when run() is called with check=True and the process returns a non-zero exit status.

cmd, returncode, stdout, stderr, output