API documentation¶
Documentation for Alfred-Workflow’s classes and methods.
See User Guide for documentation focussed on performing specific tasks.
See the main index for a list of all classes and methods.
Workflow objects¶
The Workflow
object is the main interface to this library.
Workflow
is targeted at Alfred 2. Use Workflow3
if
you want to use Alfred 3’s new features, such as
workflow variables or
more powerful modifiers.
See Workflow setup and skeleton in the User Guide for an example of how to set
up your Python script to best utilise the Workflow
object.
-
class
workflow.
Workflow
(default_settings=None, update_settings=None, input_encoding=u'utf-8', normalization=u'NFC', capture_args=True, libraries=None, help_url=None)¶ The
Workflow
object is the main interface to Alfred-Workflow.It provides APIs for accessing the Alfred/workflow environment, storing & caching data, using Keychain, and generating Script Filter feedback.
Workflow
is compatible with Alfred 2+. SubclassWorkflow3
provides additional features, only available in Alfred 3+, such as workflow variables.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 (
unicode
) – encoding of command line arguments. You should probably leave this as the default (utf-8
), which is the encoding Alfred uses. - normalization (
unicode
) – normalisation to apply to CLI args. 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, quicklookurl=None)¶ Add an item to be output to Alfred.
Parameters: - title (
unicode
) – Title shown in Alfred - subtitle (
unicode
) – Subtitle shown in Alfred - modifier_subtitles (
dict
) – Subtitles shown when modifier (CMD, OPT etc.) is pressed. Use adict
with the lowercase keyscmd
,ctrl
,shift
,alt
andfn
- arg (
unicode
) – Argument passed by Alfred as{query}
when item is actioned - autocomplete (
unicode
) – Text expanded in Alfred when item is TABbed - valid (
Boolean
) – Whether or not item can be actioned - uid (
unicode
) – Used by Alfred to remember/sort items - icon (
unicode
) – Filename of icon to use - icontype (
unicode
) – Type of icon. Must be one 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 (
unicode
) – Result type. Currently only'file'
is supported (by Alfred). This will tell Alfred to enable file actions for this item. - largetext (
unicode
) – Text to be displayed in Alfred’s large text box if user presses CMD+L on item. - copytext (
unicode
) – Text to be copied to pasteboard if user presses CMD+C on item. - quicklookurl (
unicode
) – URL to be displayed using Alfred’s Quick Look feature (tappingSHIFT
or⌘+Y
on a result).
Returns: Item
instanceSee System icons for a list of the supported system icons.
Note
Although this method returns an
Item
instance, you don’t need to hold onto it or worry about it. All 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.- title (
-
alfred_env
¶ Dict of Alfred’s environmental variables minus
alfred_
prefix.New in version 1.7.
The variables Alfred 2.4+ exports are:
Variable Description debug Set to 1
if Alfred’s debugger is open, otherwise unset.preferences Path to Alfred.alfredpreferences (where your workflows and settings are stored). preferences_localhash Machine-specific preferences are stored in Alfred.alfredpreferences/preferences/local/<hash>
(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
.
-
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)¶ Return cached data if younger than
max_age
seconds.Retrieve data from cache or re-generate and re-cache data if stale/non-existant. If
max_age
is 0, return cached data no matter how old.Parameters: - name – name of datastore
- data_func (
callable
) – function to (re-)generate data. - max_age (
int
) – maximum age of cached data in seconds
Returns: cached data, return value of
data_func
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 ( unicode
) – name of datastoreReturns: 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
-
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+ is:~/Library/Caches/com.runningwithcrayons.Alfred/Workflow Data/<bundle id>
For earlier versions:
~/Library/Caches/com.runningwithcrayons.Alfred-X/Workflow Data/<bundle id>
where
Alfred-X
may beAlfred-2
orAlfred-3
.Returns: full path to workflow’s cache directory Return type: unicode
-
cachefile
(filename)¶ Path to
filename
in workflow’s cache directory.Return absolute path to
filename
within your workflow’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 Guide for detailed information on how to enable your workflow to update itself.
Parameters: force ( Boolean
) – Force update check
-
clear_cache
(filter_func=<function <lambda>>)¶ Delete all files in workflow’s
cachedir
.Parameters: filter_func ( callable
) – Callable to determine whether a file should be deleted or not.filter_func
is called with the filename of each file in the data directory. If it 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 for Alfred 4+ is:~/Library/Application Support/Alfred/Workflow Data/<bundle id>
For earlier versions, the path is:
~/Library/Application Support/Alfred X/Workflow Data/<bundle id>
where
Alfred X` is ``Alfred 2
orAlfred 3
.Returns: full path to workflow data directory Return type: unicode
-
datafile
(filename)¶ Path to
filename
in workflow’s data directory.Return absolute path to
filename
within your workflow’sdata directory
.Parameters: filename ( unicode
) – basename of fileReturns: full path to file within data directory Return type: unicode
-
debugging
¶ Whether Alfred’s debugger is open.
Returns: True
if Alfred’s debugger is open.Return type: bool
-
decode
(text, encoding=None, normalization=None)¶ Return
text
as normalised unicode.If
encoding
and/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
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
.- text (encoded or Unicode string. If
-
delete_password
(account, service=None)¶ Delete the password stored at
service/account
.Raise
PasswordNotFound
if account is unknown.Parameters: - account (
unicode
) – name of the account the password is for, e.g. “Pinboard” - service (
unicode
) – Name of the service. By default, this is the workflow’s bundle ID
- account (
-
dumbify_punctuation
(text)¶ Convert non-ASCII punctuation to closest ASCII equivalent.
This method replaces “smart” quotes and n- or m-dashes with their workaday ASCII equivalents. This method is currently not used internally, but exists as a helper method for workflow authors.
Parameters: text ( unicode
) – text to convertReturns: text with only ASCII punctuation Return type: unicode
-
filter
(query, items, key=<function <lambda>>, ascending=False, include_score=False, min_score=0, max_results=0, match_on=127, fold_diacritics=True)¶ Fuzzy search filter. Returns list of
items
that 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 (
unicode
) – query to test items against - items (
list
ortuple
) – iterable of items to test - key (
callable
) – function to get comparison key fromitems
. Must return aunicode
string. The default simply returns the item. - ascending (
Boolean
) – set toTrue
to get worst matches first - include_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.- query (
-
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
.Raise
PasswordNotFound
exception if password doesn’t exist.Parameters: - account (
unicode
) – name of the account the password is for, e.g. “Pinboard” - service (
unicode
) – Name of the service. By default, this is the workflow’s bundle ID
Returns: account password
Return type: unicode
- 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
¶ Path to logfile.
Returns: path to logfile within workflow’s cache directory Return type: unicode
-
logger
¶ Logger that logs to both console and a log file.
If Alfred’s debugger is open, log level will be
DEBUG
, else it will beINFO
.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¶ Prefix for all magic arguments. The default value is
workflow:
so keywordconfig
would match user queryworkflow:config
.
-
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.
-
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
.
-
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-Workflow 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.
- func – Callable to call with
-
save_password
(account, password, service=None)¶ Save account credentials.
If the account exists, the old password will first be deleted (Keychain throws an error otherwise).
If something goes wrong, a
KeychainError
exception will be raised.Parameters: - account (
unicode
) – name of the account the password is for, e.g. “Pinboard” - password (
unicode
) – the password to secure - service (
unicode
) – Name of the service. By default, this is the workflow’s bundle ID
- account (
-
send_feedback
()¶ Print stored items to console/Alfred as XML.
-
set_last_version
(version=None)¶ Set
last_version_run
to current version.New in version 1.9.10.
Parameters: version ( Version
instance 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 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
-
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 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
-
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
-
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-Workflow) Return type: Version
object
-
workflowdir
¶ Path to workflow’s root directory (where
info.plist
is).Returns: full path to workflow root directory Return type: unicode
-
workflowfile
(filename)¶ Return full path to
filename
in workflow’s root directory.Parameters: filename ( unicode
) – basename of fileReturns: full path to file within data directory Return type: unicode
- default_settings (
Settings¶
Workflow
and Workflow3
objects each have a
settings
attribute that provides a simple API for storing
workflow settings.
-
class
workflow.workflow.
Settings
(filepath, defaults=None)¶ A dictionary that saves itself when changed.
Dictionary keys & values will be saved as a JSON file at
filepath
. If the file does not exist, the dictionary (and settings file) will be initialised withdefaults
.Parameters: - filepath (
unicode
) – where to save the settings - defaults (
dict
) – dict of default settings
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
).
- filepath (
Serializers¶
The serialization API provided by SerializerManager
is used by
Workflow
to store saved & cached data and settings.
You can register your own serializers on a manager.
The default manager (which supports JSON, pickle and cPickle) is at
workflow.manager
.
-
class
workflow.workflow.
SerializerManager
¶ Contains registered serializers.
New in version 1.8.
A configured instance of this class is available at
workflow.manager
.Use
register()
to register new (or replace existing) serializers, which you can specify by name when 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 (
unicode
orstr
) – Name to registerserializer
under - serializer – object with
load()
anddump()
methods
- name (
-
serializer
(name)¶ Return serializer object for
name
.Parameters: name ( unicode
orstr
) – Name of serializer to returnReturns: serializer object or None
if no such serializer is registered.
-
serializers
¶ Return names of registered serializers.
-
unregister
(name)¶ Remove registered serializer with
name
.Raises a
ValueError
if there is no such registered serializer.Parameters: name ( unicode
orstr
) – Name of serializer to removeReturns: 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
cPickle
/pickle
, so be careful which data you try to serialize as JSON.-
classmethod
dump
(obj, file_obj)¶ Serialize object
obj
to open JSON file.New in version 1.8.
Parameters: - obj (JSON-serializable data structure) – Python object to serialize
- file_obj (
file
object) – file handle
-
classmethod
-
class
workflow.workflow.
CPickleSerializer
¶ Wrapper around
cPickle
. Setsprotocol
.New in version 1.8.
This is the default serializer and the best combination of speed and flexibility.
-
classmethod
dump
(obj, file_obj)¶ Serialize object
obj
to open pickle file.New in version 1.8.
Parameters: - obj (Python object) – Python object to serialize
- file_obj (
file
object) – file handle
-
classmethod
-
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
-
classmethod
Exceptions¶
Alfred-Workflow defines the following exceptions, which may be raised by the Keychain API.
-
exception
workflow.
KeychainError
¶ Raised for unknown Keychain errors.
Raised by methods
Workflow.save_password()
,Workflow.get_password()
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).
Workflow3 objects¶
New in version 1.18.
Workflow3
is an Alfred 3-only version of
Workflow
that supports Alfred 3’s new features.
It supports setting Workflow variables and
the more advanced modifiers
supported by Alfred 3.
In order for the feedback mechanism to work correctly, it’s important
to create Item3
and Modifier
objects via the
add_item()
and Item3.add_modifier()
methods
respectively. If you instantiate Item3
or Modifier
objects
directly, the current Workflow3
object won’t be aware of
them, and they won’t be sent to Alfred when you call
send_feedback()
.
-
class
workflow.
Workflow3
(**kwargs)¶ Workflow class that generates Alfred 3+ feedback.
It is a subclass of
Workflow
and most of its methods are documented there.-
item_class
¶ class – Class used to generate feedback items.
-
variables
¶ dict – Top level workflow variables.
-
add_item
(title, subtitle=u'', arg=None, autocomplete=None, valid=False, uid=None, icon=None, icontype=None, type=None, largetext=None, copytext=None, quicklookurl=None, match=None)¶ Add an item to be output to Alfred.
Parameters: match (unicode, optional) – If you have “Alfred filters results” turned on for your Script Filter, Alfred (version 3.5 and above) will filter against this field, not title
.In Alfred 4.1+ and Alfred-Workflow 1.40+,
arg
may also be alist
ortuple
.See
Workflow.add_item()
for the main documentation and other parameters.The key difference is that this method does not support the
modifier_subtitles
argument. Use theadd_modifier()
method instead on the returned item instead.Returns: Alfred feedback item. Return type: Item3
-
cache_data
(name, data, session=False)¶ Cache API with session-scoped expiry.
New in version 1.25.
Parameters: name
anddata
are the same as for thecache_data()
method onWorkflow
.If
session
isTrue
, thenname
is prefixed withsession_id
.
-
cached_data
(name, data_func=None, max_age=60, session=False)¶ Cache API with session-scoped expiry.
New in version 1.25.
Parameters: name
,data_func
andmax_age
are the same as for thecached_data()
method onWorkflow
.If
session
isTrue
, thenname
is prefixed withsession_id
.
-
clear_session_cache
(current=False)¶ Remove session data from the cache.
New in version 1.25.
Changed in version 1.27.
By default, data belonging to the current session won’t be deleted. Set
current=True
to also clear current session.Parameters: current (bool, optional) – If True
, also remove data for current session.
-
getvar
(name, default=None)¶ Return value of workflow variable for
name
ordefault
.Parameters: - name (unicode) – Variable name.
- default (None, optional) – Value to return if variable is unset.
Returns: Value of variable if set or
default
.Return type: unicode or
default
-
item_class
alias of
Item3
-
obj
¶ Feedback formatted for JSON serialization.
Returns: Data suitable for Alfred 3 feedback. Return type: dict
-
rerun
¶ How often (in seconds) Alfred should re-run the Script Filter.
-
send_feedback
()¶ Print stored items to console/Alfred as JSON.
-
session_id
¶ A unique session ID every time the user uses the workflow.
New in version 1.25.
The session ID persists while the user is using this workflow. It expires when the user runs a different workflow or closes Alfred.
-
setvar
(name, value, persist=False)¶ Set a “global” workflow variable.
Changed in version 1.33.
These variables are always passed to downstream workflow objects.
If you have set
rerun
, these variables are also passed back to the script when Alfred runs it again.Parameters: - name (unicode) – Name of variable.
- value (unicode) – Value of variable.
- persist (bool, optional) – Also save variable to
info.plist
?
-
warn_empty
(title, subtitle=u'', icon=None)¶ Add a warning to feedback if there are no items.
New in version 1.31.
Add a “warning” item to Alfred feedback if no other items have been added. This is a handy shortcut to prevent Alfred from showing its fallback searches, which is does if no items are returned.
Parameters: - title (unicode) – Title of feedback item.
- subtitle (unicode, optional) – Subtitle of feedback item.
- icon (str, optional) – Icon for feedback item. If not
specified,
ICON_WARNING
is used.
Returns: Newly-created item.
Return type:
-
Workflow variables¶
New in version 1.18.
Alfred 3 allows you to pass around variables in your workflows. It passes
these to your scripts as environment variables (access them with
os.getenv()
), and you can pass variables back to Alfred via JSON.
In Script Filters, use the setvar()
methods on Workflow3
,
Item3
and Modifier
.
In Run Script actions, use the Variables
.
See Workflow variables in the User Guide for more information.
Item3
and Modifier
are documented below, in the
Advanced modifiers section.
-
class
workflow.
Variables
(arg=None, **variables)¶ Workflow variables for Run Script actions.
This class allows you to set workflow variables from Run Script actions.
It is a subclass of
dict
.>>> v = Variables(username='deanishe', password='hunter2') >>> v.arg = u'output value' >>> print(v)
See Setting variables from Run Script actions in the User Guide for more information.
Parameters: - arg (unicode or list, optional) – Main output/
{query}
. - **variables – Workflow variables to set.
In Alfred 4.1+ and Alfred-Workflow 1.40+,
arg
may also be alist
ortuple
.-
arg
¶ unicode or list – Output value (
{query}
). In Alfred 4.1+ and Alfred-Workflow 1.40+,arg
may also be alist
ortuple
.
-
config
¶ dict – Configuration for downstream workflow element.
- arg (unicode or list, optional) – Main output/
Advanced modifiers¶
New in version 1.18.
Changed in version 1.27.
You can specify alternate arg
, subtitle
and variables if a
Script Filter result is actioned while holding down a modifier key.
As of Alfred-Workflow version 1.27 and Alfred version 3.4.1, you can also specify an alternative icon for a modifier.
Add a modifier to an item using Item3.add_modifier()
, and configure
the Modifier
via its attributes and setvar()
method.
-
class
workflow.workflow3.
Item3
(title, subtitle=u'', arg=None, autocomplete=None, match=None, valid=False, uid=None, icon=None, icontype=None, type=None, largetext=None, copytext=None, quicklookurl=None)¶ Represents a feedback item for Alfred 3+.
Generates Alfred-compliant JSON for a single item.
Don’t use this class directly (as it then won’t be associated with any
Workflow3
object), but rather useWorkflow3.add_item()
. Seeadd_item()
for details of arguments.-
add_modifier
(key, subtitle=None, arg=None, valid=None, icon=None, icontype=None)¶ Add alternative values for a modifier key.
Parameters: - key (unicode) – Modifier key, e.g.
"cmd"
or"alt"
- subtitle (unicode, optional) – Override item subtitle.
- arg (unicode, optional) – Input for following action.
- valid (bool, optional) – Override item validity.
- icon (unicode, optional) – Filepath/UTI of icon.
- icontype (unicode, optional) – Type of icon. See
Workflow.add_item()
for valid values.
In Alfred 4.1+ and Alfred-Workflow 1.40+,
arg
may also be alist
ortuple
.Returns: Configured Modifier
.Return type: Modifier - key (unicode) – Modifier key, e.g.
-
getvar
(name, default=None)¶ Return value of workflow variable for
name
ordefault
.Parameters: - name (unicode) – Variable name.
- default (None, optional) – Value to return if variable is unset.
Returns: Value of variable if set or
default
.Return type: unicode or
default
-
obj
¶ Item formatted for JSON serialization.
Returns: Data suitable for Alfred 3 feedback. Return type: dict
-
setvar
(name, value)¶ Set a workflow variable for this Item.
Parameters: - name (unicode) – Name of variable.
- value (unicode) – Value of variable.
-
-
class
workflow.workflow3.
Modifier
(key, subtitle=None, arg=None, valid=None, icon=None, icontype=None)¶ Modify
Item3
arg/icon/variables when modifier key is pressed.Don’t use this class directly (as it won’t be associated with any
Item3
), but rather useItem3.add_modifier()
to add modifiers to results.>>> it = wf.add_item('Title', 'Subtitle', valid=True) >>> it.setvar('name', 'default') >>> m = it.add_modifier('cmd') >>> m.setvar('name', 'alternate')
See Workflow variables in the User Guide for more information and example usage.
Parameters: - key (unicode) – Modifier key, e.g.
"cmd"
,"alt"
etc. - subtitle (unicode, optional) – Override default subtitle.
- arg (unicode, optional) – Argument to pass for this modifier.
- valid (bool, optional) – Override item’s validity.
- icon (unicode, optional) – Filepath/UTI of icon to use
- icontype (unicode, optional) – Type of icon. See
Workflow.add_item()
for valid values.
-
arg
¶ unicode – Arg to pass to following action.
-
config
¶ dict – Configuration for a downstream element, such as a File Filter.
-
icon
¶ unicode – Filepath/UTI of icon.
-
icontype
¶ unicode – Type of icon. See
Workflow.add_item()
for valid values.
-
key
¶ unicode – Modifier key (see above).
-
subtitle
¶ unicode – Override item subtitle.
-
valid
¶ bool – Override item validity.
-
variables
¶ dict – Workflow variables set by this modifier.
-
getvar
(name, default=None)¶ Return value of workflow variable for
name
ordefault
.Parameters: - name (unicode) – Variable name.
- default (None, optional) – Value to return if variable is unset.
Returns: Value of variable if set or
default
.Return type: unicode or
default
-
obj
¶ Modifier formatted for JSON serialization for Alfred 3.
Returns: Modifier for serializing to JSON. Return type: dict
-
setvar
(name, value)¶ Set a workflow variable for this Item.
Parameters: - name (unicode) – Name of variable.
- value (unicode) – Value of variable.
- key (unicode) – Modifier key, e.g.
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 (unicode) – 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.
HTTP requests¶
workflow.web
provides a simple API for retrieving data from the Web
modelled on the excellent requests library.
The purpose of workflow.web
is to cover trivial cases at just 0.5% of
the size of requests.
Danger
As workflow.web
is based on Python 2’s standard HTTP libraries,
there are two important problems with SSL connections.
Python versions older than 2.7.9 (i.e. pre-Yosemite) do not verify SSL certificates when establishing HTTPS connections.
As a result, you must not use this module for sensitive connections unless you’re certain it will only run on 2.7.9/Yosemite and later. If your workflow is Alfred 3-only, this requirement is met.
Secondly, versions of macOS older than High Sierra (10.13) have an extremely outdated version of OpenSSL, which is incompatible with many servers’ SSL configuration.
Consequently, workflow.web
cannot connect to such servers.
As this includes GitHub’s SSL configuration, the
update mechanism only works on High Sierra
and later.
-
workflow.web.
get
(url, params=None, headers=None, cookies=None, auth=None, timeout=60, allow_redirects=True, stream=False)¶ Initiate a GET request. Arguments as for
request()
.Returns: Response
instance
-
workflow.web.
post
(url, params=None, data=None, headers=None, cookies=None, files=None, auth=None, timeout=60, allow_redirects=False, stream=False)¶ Initiate a POST request. Arguments as for
request()
.Returns: Response
instance
-
workflow.web.
request
(method, url, params=None, data=None, headers=None, cookies=None, files=None, auth=None, timeout=60, allow_redirects=False, stream=False)¶ Initiate an HTTP(S) request. Returns
Response
object.Parameters: - method (unicode) – ‘GET’ or ‘POST’
- url (unicode) – URL to open
- params (dict) – mapping of URL parameters
- data (dict or str) – mapping of form data
{'field_name': 'value'}
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 # unicode, decoded according to charset in HTTP header/meta tag u'<html> ...' >>> r.json() # content parsed as JSON
-
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: Returns: iterator
-
json
()¶ Decode response contents as JSON.
Returns: object decoded from JSON Return type: list, dict or unicode
-
raise_for_status
()¶ Raise stored error if one occurred.
error will be instance of
urllib2.HTTPError
-
save_to_path
(filepath)¶ Save retrieved data to file at
filepath
.Parameters: filepath – Path to save retrieved data.
-
Workflow updates¶
New in version 1.9.
Add self-updating capabilities to your workflow. It regularly (every day by default) fetches the latest releases from the specified GitHub repository.
Currently, only updates from GitHub releases are supported.
Important
Alfred-Workflow will check for updates, but will neither install them nor notify the user that an update is available.
Normally, you would not use workflow.update
directly, but use the
corresponding methods on Workflow
and
Workflow3
.
Please see Self-updating in the User Guide for information on how to enable automatic updates in your workflow.
-
workflow.update.
check_update
(repo, current_version, prereleases=False, alfred_version=None)¶ Check whether a newer release is available on GitHub.
Parameters: - repo (unicode) –
username/repo
for workflow’s GitHub repo - current_version (unicode) – the currently installed version of the workflow. Semantic versioning is required.
- prereleases (bool) – Whether to include pre-releases.
- alfred_version (unicode) – 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.
- repo (unicode) –
-
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.
-
url
¶ str – URL of workflow file.
-
filename
¶ str – Filename of workflow file.
-
version
¶ Version – Semantic version of workflow.
-
prerelease
¶ bool – Whether version is a pre-release.
-
alfred_version
¶ Version – Minimum compatible version of Alfred.
-
alfred_version
Minimum Alfred version based on filename extension.
-
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
()¶ Match version and pre-release/build information in version strings
-
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 (unicode) – URL to .alfredworkflow file in GitHub repo Returns: path to downloaded file Return type: unicode
Notifications¶
New in version 1.15.
Note
Notifications aren’t available in version of macOS older than
10.8/Mountain Lion. Calling notify()
on these systems will
silently do nothing.
notify
allows you to post notifications via macOS’s
Notification Center at any time, not just at the end of your script.
Furthermore, it uses your workflow’s icon, not Alfred’s.
The main API is a single function, notify()
.
It works by copying a simple application to your workflow’s data directory. It replaces the application’s icon with your workflow’s icon and then calls the application to post notifications.
-
workflow.notify.
notify
(title=u'', text=u'', sound=None)¶ Post notification via Notify.app helper.
Parameters: Raises: ValueError
– Raised if bothtitle
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: - cmd (list) – Command arguments to pass to
-
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
.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:
-
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:
-
class
workflow.util.
AppInfo
(name, path, bundleid)¶ Information about an installed application.
Returned by
appinfo()
. All attributes are Unicode.-
name
¶ Name of the application, e.g.
u'Safari'
.
-
path
¶ Path to the application bundle, e.g.
u'/Applications/Safari.app'
.
-
bundleid
¶ Application’s bundle ID, e.g.
u'com.apple.Safari'
.
-
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.Parameters: Returns: Decoded, optionally normalised, Unicode string.
Return type: unicode
-
workflow.util.
utf8ify
(s)¶ Ensure string is a bytestring.
New in version 1.31.
Returns str objects unchanced, encodes unicode objects to UTF-8, and calls
str()
on anything else.Parameters: s (object) – A Python object Returns: UTF-8 string or string representation of s. Return type: str
-
workflow.util.
applescriptify
(s)¶ Escape string for insertion into an AppleScript string.
New in version 1.31.
Replaces
"
with “& quote &”. Use this function if you want to insert a string into an AppleScript script:>>> applescriptify('g "python" test') 'g " & quote & "python" & quote & "test'
Parameters: s (unicode) – Unicode string to escape. Returns: Escaped string. Return type: unicode
Alfred’s API¶
Alfred-Workflow 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:
-
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:
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 (unicode, 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 (unicode, 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 (unicode) – 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 (unicode) – Name of theme Alfred should use.
Miscellaneous¶
These utility classes and functions are used internally by Alfred-Workflow, 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 (unicode) – 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.
-
delay
¶ float – How often to check (in seconds) whether the lock can be acquired.
-
lockfile
¶ unicode – Path of the lockfile.
-
timeout
¶ float – How long to wait to acquire the lock.
-
acquire
(blocking=True)¶ Acquire the lock if possible.
If the lock is in use and
blocking
isFalse
, returnFalse
.Otherwise, check every
delay
seconds until it acquires lock or exceeds attr:timeout and raises anAcquisitionError
.
-
locked
¶ True
if file is locked by this instance.
-
release
()¶ Release the lock by deleting self.lockfile.
-
class
workflow.util.
uninterruptible
(func, class_name='')¶ Decorator that postpones SIGTERM until wrapped function returns.
New in version 1.12.
Important
This decorator is NOT thread-safe.
As of version 2.7, Alfred allows Script Filters to be killed. If your workflow is killed in the middle of critical code (e.g. writing data to disk), this may corrupt your workflow’s data.
Use this decorator to wrap critical functions that must complete. If the script is killed while a wrapped function is executing, the SIGTERM will be caught and handled after your function has finished executing.
Alfred-Workflow uses this internally to ensure its settings, data and cache writes complete.
-
signal_handler
(signum, frame)¶ Called when process receives SIGTERM.
-
-
workflow.util.
atomic_writer
(*args, **kwds)¶ Atomic file writer.
New in version 1.12.
Context manager that ensures the file is only written if the write succeeds. The data is first written to a temporary file.
Parameters: - fpath (
unicode
) – path of file to write to. - mode (string) – sames as for
open()
- fpath (
Images & sounds¶
-
workflow.notify.
convert_image
(inpath, outpath, size)¶ Convert an image file using
sips
.Parameters: Raises: RuntimeError
– Raised ifsips
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 ificonutil
orsips
fail.
Exceptions¶
The following exceptions, may be raised by utility functions.
-
exception
workflow.util.
AcquisitionError
¶ Raised if a lock cannot be acquired.
-
exception
subprocess.
CalledProcessError
(returncode, cmd, output=None)¶ This exception is raised when a process run by check_call() or check_output() returns a non-zero exit status.
-
cmd, returncode, output
-