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 withdefault_settings
.update_settings (
dict
) – settings for updating your workflow from GitHub releases. The only required key isgithub_slug
, whose value must take the form ofusername/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. SeeWorkflow.decode()
for more details.capture_args (
Boolean
) – Capture and act onworkflow:*
arguments. See Magic arguments for details.libraries (
tuple
orlist
) – sequence of paths to directories containing libraries. These paths will be prepended tosys.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 theworkflow:help
magic argument.
- item_class¶
Class used to generate feedback items.
- Type:
class
- 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 Alfredsubtitle (
str
) – Subtitle shown in Alfredarg (
str
,list
ortuple
) – Argument passed by Alfred as{query}
when item is actionedautocomplete (
str
) – Text expanded in Alfred when item is TABbedvalid (
Boolean
) – Whether or not item can be actioneduid (
str
) – Used by Alfred to remember/sort itemsicon (
str
) – Filename of icon to useicontype (
str
) – Type of icon. Must be one ofNone
,'filetype'
or'fileicon'
. Use'filetype'
whenicon
is a filetype such as'public.folder'
. Use'fileicon'
when you wish to use the icon of the file specified asicon
, e.g.icon='/Applications/Safari.app', icontype='fileicon'
. Leave as None ificon
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 (tappingSHIFT
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 generatedItem
instances are also collected internally and sent to Alfred whensend_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 theadd_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>
(seepreferences
above for the path toAlfred.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
= Neverversion
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
andtheme_subtext
, which are integers.- Returns:
dict
of Alfred’s environmental variables without thealfred_
prefix, e.g.preferences
,workflow_data
.
- property args¶
Return command line args as normalised unicode.
Args are decoded and normalised via
decode()
.The encoding and normalization are the
input_encoding
andnormalization
arguments passed toWorkflow
(UTF-8
andNFC
are the defaults).If
Workflow
is called withcapture_args=True
(the default),Workflow
will look for certainworkflow:*
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 undername
. Ifdata
isNone
, the corresponding cache file will be deleted.- Parameters:
name (
str
) – name of datastoredata (
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
isTrue
, thenname
is prefixed withsession_id
.
- property cache_serializer¶
Name of default cache serializer.
New in version 1.8.
This serializer is used by
cache_data()
andcached_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 datastoredata_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
orNone
ifdata_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 thanmax_age
old, elseFalse
- 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:
- cachefile(filename)¶
Path to
filename
in workflow’s cache directory.Return absolute path to
filename
within your workflow’scache 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 returnsTrue
, 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 returnsTrue
, 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()
andstored_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:
- datafile(filename)¶
Path to
filename
in workflow’s data directory.Return absolute path to
filename
within your workflow’sdata 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/ornormalization
isNone
, theinput_encoding``and ``normalization
parameters passed toWorkflow
are used.- Parameters:
text (encoded or Unicode string. If
text
is already a Unicode string, it will only be normalised.) – stringencoding (
str
orNone
) – The text encoding to use to decodetext
to Unicode.normalization (
str
orNone
) – The nomalisation form to apply totext
.
- 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 (viaweb
orjson
).macOS, on the other hand, uses “NFD” normalisation (nearly), so data coming from the system (e.g. via
subprocess
oros.listdir()
/os.path
) may not match. You should either normalise this data, too, or change the default normalisation used byWorkflow
.
- 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 matchquery
.query
is case-insensitive. Any item that does not contain the entirety ofquery
is rejected.If
query
is an empty string or contains only whitespace, all items will match.- Parameters:
query (
str
) – query to test items againstitems (
list
ortuple
) – iterable of items to testkey (
callable
) – function to get comparison key fromitems
. Must return astr
string. The default simply returns the item.ascending (
Boolean
) – set toTrue
to get worst matches firstinclude_score (
Boolean
) – Useful for debugging the scoring algorithm. IfTrue
, 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 ofMATCH_*
constants (see below).fold_diacritics (
Boolean
) – Convert search keys to ASCII-only characters ifquery
only contains ASCII characters.
- Returns:
list of
items
matchingquery
or list of(item, score, rule)
tuples ifinclude_score
isTrue
.rule
is theMATCH_*
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:MATCH_STARTSWITH
Item search key starts with
query
(case-insensitive).
MATCH_CAPITALS
The list of capital letters in item search key starts with
query
(query
may be lower-case). E.g.,of
would matchOmniFocus
,gc
would matchGoogle Chrome
.
MATCH_ATOM
Search key is split into “atoms” on non-word characters (.,-,’ etc.). Matches if
query
is one of these atoms (case-insensitive).
MATCH_INITIALS_STARTSWITH
Initials are the first characters of the above-described “atoms” (case-insensitive).
MATCH_INITIALS_CONTAIN
query
is a substring of the above-described initials.
MATCH_INITIALS
Combination of (4) and (5).
MATCH_SUBSTRING
query
is a substring of item search key (case-insensitive).
MATCH_ALLCHARS
All characters in
query
appear in item search key in the same order (case-insensitive).
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), usematch_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
isTrue
(the default), andquery
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
ifversion
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
ordefault
.- 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
- 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 orNone
- 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 beINFO
.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 astr
string.By default, the magic arguments documented here are registered.
- magic_prefix¶
Prefix for all magic arguments. The default value is
workflow:
so keywordconfig
would match user queryworkflow: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:
- open_help()¶
Open
help_url
in default browser.
- 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 theupdate_settings
dict, elseFalse
.
- property rerun¶
How often (in seconds) Alfred should re-run the Script Filter.
- reset()¶
Delete workflow settings, cache and data.
- run(func, text_errors=False)¶
Call
func
to run your workflow.- Parameters:
func – Callable to call with
self
(i.e. theWorkflow
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 withWorkflow
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 secureservice (
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 orstr
) – version to store (default is current version)- Returns:
True
if version is saved, elseFalse
- 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 atsettings_path
or if that doesn’t exist, with thedefault_settings
dict
passed toWorkflow
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.
- 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, elseFalse
- store_data(name, data, serializer=None)¶
Save data to data directory.
New in version 1.8.
If
data
isNone
, 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 undername
.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, elseFalse
- 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, theversion
file located in the workflow’s root directory orinfo.plist
. ReturnNone
if none exists orValueError
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.
- property workflowdir¶
Path to workflow’s root directory (where
info.plist
is).- Returns:
full path to workflow root directory
- Return type:
- 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 withdefaults
.An appropriate instance is provided by
Workflow
instances atWorkflow.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 besettings.json
in your workflow’s data directory (seedatadir
).
- 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 besettings.json
in your workflow’s data directory (seedatadir
).
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 callingWorkflow
data storage methods.See Serialization of stored/cached data and Persistent data for further information.
- register(name, serializer)¶
Register
serializer
object undername
.Raises
AttributeError
ifserializer
in invalid.Note
name
will be used as the file extension of the saved files.- Parameters:
name (
str
) – Name to registerserializer
underserializer – object with
load()
anddump()
methods
- serializer(name)¶
Return serializer object for
name
.- Parameters:
name (
str
orbytes
) – 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
orbytes
) – Name of serializer to remove- Returns:
serializer object
- class workflow.workflow.JSONSerializer¶
Wrapper around
json
. Setsindent
andencoding
.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
- class workflow.workflow.PickleSerializer¶
Wrapper around
pickle
. Setsprotocol
.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
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()
andWorkflow.delete_password()
whensecurity
CLI app returns an unknown error code.
- exception workflow.PasswordNotFound¶
Password not in Keychain.
Raised by method
Workflow.get_password()
whenaccount
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:
name (str) – name of job
args – arguments passed as first argument to
subprocess.call()
**kwargs – keyword arguments to
subprocess.call()
- Returns:
exit code of sub-process
- Return type:
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.
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'}
orstr
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:
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, orapplication/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 therequests
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:
- 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.
- json()¶
Decode response contents as JSON.
- 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:
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 repocurrent_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, elseFalse
- Return type:
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, elseFalse
Helpers¶
- class workflow.update.Download(url, filename, version, prerelease=False)¶
A workflow file that is available for download.
- 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.
- 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.
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:
- Raises:
ValueError – Raised if both
title
andtext
are empty.- Returns:
True
if notification was posted, elseFalse
.- Return type:
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:
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:
- 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, otherwisescript
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 torun_command()
.
- Returns:
Output of run command.
- Return type:
- workflow.util.run_jxa(script, *args)¶
Execute a JXA script and return its output.
New in version 1.31.
Wrapper around
run_applescript()
that passeslang=JavaScript
.
- 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.
- 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'
.
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 formnorm
if specified.
- 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'
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.
- 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.
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.
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:
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
. OtherLockFile
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. Iftimeout
is 0 (the default), wait forever.delay (float, optional) – How often to check (in seconds) if lock has been released.
- acquire(blocking=True)¶
Acquire the lock if possible.
If the lock is in use and
blocking
isFalse
, returnFalse
.Otherwise, check every
delay
seconds until it acquires lock or exceeds attr:timeout and raises anAcquisitionError
.
- 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.
Images & sounds¶
- workflow.notify.convert_image(inpath, outpath, size)¶
Convert an image file using
sips
.- Parameters:
- 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:
- Raises:
RuntimeError – Raised if
iconutil
orsips
fail.
- workflow.notify.validate_sound(sound)¶
Coerce
sound
to valid sound name.Returns
None
for invalid sounds. Sound names can be found inSystem Preferences > Sound > Sound Effects
or located at/System/Library/Sounds
.
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