The Workflow Object¶
The Workflow
object is the main interface to this library.
See Workflow setup and skeleton in the User Manual for an example of how to set
up your Python script to best utilise the Workflow
object.
-
class
workflow.workflow.
Workflow
(default_settings=None, update_settings=None, input_encoding=u'utf-8', normalization=u'NFC', capture_args=True, libraries=None, help_url=None)¶ Create new
Workflow
instance.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. This must be adict
that containsgithub_slug
andversion
keys.github_slug
is of the formusername/repo
andversion
must correspond to the tag of a release. See Self-Updating for more information. - input_encoding (
unicode
) – encoding of command line arguments - normalization (
unicode
) – normalisation 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 (
unicode
orstr
) – 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.
-
add_item
(title, subtitle=u'', modifier_subtitles=None, arg=None, autocomplete=None, valid=False, uid=None, icon=None, icontype=None, type=None, largetext=None, copytext=None)¶ Add an item to be output to Alfred
Passes arguments through to
XMLGenerator
methodadd_item()
.
-
alfred_env
¶ Alfred’s environmental variables minus the
alfred_
prefix.New in version 1.7.
The variables Alfred 2.4+ exports are:
Variable Description alfred_preferences Path to Alfred.alfredpreferences (where your workflows and settings are stored). alfred_preferences_localhash Machine-specific preferences are stored in Alfred.alfredpreferences/preferences/local/<hash>
(seealfred_preferences
above for the path toAlfred.alfredpreferences
)alfred_theme ID of selected theme alfred_theme_background Background colour of selected theme in format rgba(r,g,b,a)
alfred_theme_subtext Show result subtext. 0
= Always,1
= Alternative actions only,2
= Selected result only,3
= Neveralfred_version Alfred version number, e.g. '2.4'
alfred_version_build Alfred build number, e.g. 277
alfred_workflow_bundleid Bundle ID, e.g. net.deanishe.alfred-mailto
alfred_workflow_cache Path to workflow’s cache directory alfred_workflow_data Path to workflow’s data directory alfred_workflow_name Name of current workflow alfred_workflow_uid UID of workflow 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
.
-
args
¶ Return command line args as normalised unicode.
Args are decoded and normalised via
decode()
.The encoding and normalisation 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.
-
bundleid
¶ Workflow bundle ID from environmental vars or
info.plist
.Returns: bundle ID Return type: unicode
-
cache_data
(name, data)¶ Save
data
to cache undername
.If
data
isNone
, the corresponding cache file will be deleted.Parameters: - name – name of datastore
- data – data to store. This may be any object supported by the cache serializer
-
cache_serializer
¶ Name of default cache serializer.
New in version 1.8.
This serializer is used by
cache_data()
andcached_data()
See
SerializerManager
for details.Returns: serializer name Return type: unicode
-
cached_data
(name, data_func=None, max_age=60)¶ Retrieve data from cache or re-generate and re-cache data if stale/non-existant. If
max_age
is 0, return cached data no matter how old.Parameters: - name – name of datastore
- data_func (
callable
) – function to (re-)generate data. - max_age (
int
) – maximum age of cached data in seconds
Returns: cached data, return value of
data_func
orNone
ifdata_func
is not set
-
cached_data_age
(name)¶ Return age of data cached at name in seconds or 0 if cache doesn’t exist
Parameters: name ( unicode
) – name of datastoreReturns: age of datastore in seconds Return type: int
-
cached_data_fresh
(name, max_age)¶ Is data cached at name less than max_age 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
-
cachedir
¶ Path to workflow’s cache directory.
The cache directory is a subdirectory of Alfred’s own cache directory in
~/Library/Caches
. The full path is:~/Library/Caches/com.runningwithcrayons.Alfred-2/Workflow Data/<bundle id>
Returns: full path to workflow’s cache directory Return type: unicode
-
cachefile
(filename)¶ Return full path to
filename
within your workflow’scache directory
.Parameters: filename ( unicode
) – basename of fileReturns: full path to file within cache directory Return type: unicode
-
check_update
(force=False)¶ Call update script if it’s time to check for a new release
New in version 1.9.
The update script will be run in the background, so it won’t interfere in the execution of your workflow.
See Self-updating in the User Manual for detailed information on how to enable your workflow to update itself.
Parameters: force ( Boolean
) – Force update check
-
clear_cache
(filter_func=<function <lambda>>)¶ Delete all files in workflow’s
cachedir
.Parameters: filter_func ( callable
) – Callable to determine whether a file should be deleted or not.filter_func
is called with the filename of each file in the data directory. If it returnsTrue
, the file will be deleted. By default, all files will be deleted.
-
clear_data
(filter_func=<function <lambda>>)¶ Delete all files in workflow’s
datadir
.Parameters: filter_func ( callable
) – Callable to determine whether a file should be deleted or not.filter_func
is called with the filename of each file in the data directory. If it returnsTrue
, the file will be deleted. By default, all files will be deleted.
-
clear_settings
()¶ Delete workflow’s
settings_path
.
-
data_serializer
¶ Name of default data serializer.
New in version 1.8.
This serializer is used by
store_data()
andstored_data()
See
SerializerManager
for details.Returns: serializer name Return type: unicode
-
datadir
¶ Path to workflow’s data directory.
The data directory is a subdirectory of Alfred’s own data directory in
~/Library/Application Support
. The full path is:~/Library/Application Support/Alfred 2/Workflow Data/<bundle id>
Returns: full path to workflow data directory Return type: unicode
-
datafile
(filename)¶ Return full path to
filename
within your workflow’sdata directory
.Parameters: filename ( unicode
) – basename of fileReturns: full path to file within data directory Return type: unicode
-
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.) – string - encoding (
unicode
orNone
) – The text encoding to use to decodetext
to Unicode. - normalization (
unicode
orNone
) – The nomalisation form to apply totext
.
Returns: decoded and normalised
unicode
- text (encoded or Unicode string. If
-
delete_password
(account, service=None)¶ Delete the password stored at
service/account
. RaisesPasswordNotFound
if account is unknown.Parameters: - account (
unicode
) – name of the account the password is for, e.g. “Pinboard” - service (
unicode
) – Name of the service. By default, this is the workflow’s bundle ID
- account (
-
filter
(query, items, key=<function <lambda>>, ascending=False, include_score=False, min_score=0, max_results=0, match_on=127, fold_diacritics=True)¶ Fuzzy search filter. Returns list of
items
that matchquery
.query
is case-insensitive. Any item that does not contain the entirety ofquery
is rejected.See
workflow.search.filter()
for detailed documentation.
-
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 ( unicode
) – text to convertReturns: text containing only ASCII characters Return type: unicode
-
get_password
(account, service=None)¶ Retrieve the password saved at
service/account
. RaisePasswordNotFound
exception if password doesn’t exist.Parameters: - account (
unicode
) – name of the account the password is for, e.g. “Pinboard” - service (
unicode
) – Name of the service. By default, this is the workflow’s bundle ID
Returns: account password
Return type: unicode
- account (
-
item_class
¶ alias of
Item
-
last_version_run
¶ Return version of last version to run (or
None
)New in version 1.9.10.
Returns: Version
instance orNone
-
logfile
¶ Return path to logfile
Returns: path to logfile within workflow’s cache directory Return type: unicode
-
logger
¶ Create and return a logger that logs to both console and a log file.
Use
open_log()
to open the log file in Console.Returns: an initialised Logger
-
magic_arguments
= None¶ Mapping of available magic arguments. The built-in magic arguments are registered by default. To add your own magic arguments (or override built-ins), add a key:value pair where the key is what the user should enter (prefixed with
magic_prefix
) and the value is a callable that will be called when the argument is entered. If you would like to display a message in Alfred, the function should return aunicode
string.By default, the magic arguments documented here are registered.
-
magic_prefix
= None¶ The prefix for all magic arguments. Default is
workflow:
-
name
¶ Workflow name from Alfred’s environmental vars or
info.plist
.Returns: workflow name Return type: unicode
-
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.
-
run
(func)¶ Call
func
to run your workflowParameters: func – Callable to call with self
(i.e. theWorkflow
instance) as first argument.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
base.KeychainError
exception will be raised.Parameters: - account (
unicode
) – name of the account the password is for, e.g. “Pinboard” - password (
unicode
) – the password to secure - service (
unicode
) – Name of the service. By default, this is the workflow’s bundle ID
- account (
-
send_feedback
()¶ Print stored items to console/Alfred as XML.
-
set_last_version
(version=None)¶ Set
last_version_run
to current versionNew in version 1.9.10.
Parameters: version ( Version
instance orunicode
) – version to store (default is current version)Returns: True
if version is saved, elseFalse
-
settings
¶ Return a dictionary subclass that saves itself when changed.
See Settings in the User Manual for more information on how to use
settings
and important limitations on what it can do.Returns: PersistentDict
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: PersistentDict
instance
-
settings_path
¶ Path to settings file within workflow’s data directory.
Returns: path to settings.json
fileReturn type: unicode
-
start_update
()¶ Check for update and download and install new workflow file
New in version 1.9.
See Self-updating in the User Manual 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.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.New in version 1.8.
Parameters: name – name of datastore
-
update_available
¶ Is an update available?
New in version 1.9.
See Self-updating in the User Manual for detailed information on how to enable your workflow to update itself.
Returns: True
if an update is available, elseFalse
-
version
¶ Return the version of the workflow
New in version 1.9.10.
Get the version from the
update_settings
dict passed on instantiation or theversion
file located in the workflow’s root directory. ReturnNone
if neither exist orValueError
if the version number is invalid (i.e. not semantic).Returns: Version of the workflow (not Alfred-Workflow) Return type: Version
object
-
workflowdir
¶ Path to workflow’s root directory (where
info.plist
is).Returns: full path to workflow root directory Return type: unicode
-
workflowfile
(filename)¶ Return full path to
filename
in workflow’s root dir (whereinfo.plist
is).Parameters: filename ( unicode
) – basename of fileReturns: full path to file within data directory Return type: unicode
- default_settings (