11.2.2. keypirinha_util module¶
The keypirinha_util module offers some utility features frequently required
by the plugin developer.
11.2.2.1. Reference¶
-
class
keypirinha_util.FileAttr¶ Bases:
enum.IntEnumFile attribute flags returned by
file_attributes().-
COMPRESSED= <FileAttr.COMPRESSED: 524288>¶ File is compressed.
-
DIR= <FileAttr.DIR: 2>¶ Path points to a directory.
-
ENCRYPTED= <FileAttr.ENCRYPTED: 1048576>¶ File is encrypted.
-
FILE= <FileAttr.FILE: 4>¶ Path points to a regular file.
-
HIDDEN= <FileAttr.HIDDEN: 262144>¶ File is hidden.
-
LINK= <FileAttr.LINK: 8>¶ Path points to a link file (
.lnk).
-
READONLY= <FileAttr.READONLY: 131072>¶ File is read-only.
-
REMOVABLE= <FileAttr.REMOVABLE: 4194304>¶ File is a removable media or is stored on a removable media.
-
SHARED= <FileAttr.SHARED: 2097152>¶ File is shared.
-
-
class
keypirinha_util.ScanFlags¶ Bases:
enum.IntEnumThe flags to pass to
scan_directory().-
ABORT_ON_ERROR= <ScanFlags.ABORT_ON_ERROR: 16>¶ Abort if any error occurs while scanning a sub-folder
-
CASE_SENSITIVE= <ScanFlags.CASE_SENSITIVE: 8>¶ Case-sensitive scan (default is case-unsensitive)
-
DEFAULT= <ScanFlags.DEFAULT: 3>¶ Combination of
SCAN_FILES|SCAN_DIRS
-
DIRS= <ScanFlags.DIRS: 2>¶ List directories
-
FILES= <ScanFlags.FILES: 1>¶ List files (i.e. – everything that is not a directory)
-
HIDDEN= <ScanFlags.HIDDEN: 4>¶ List hidden files
-
-
keypirinha_util.browse_directory(plugin, base_dir, check_base_dir=True, search_terms='', store_score=False, show_dirs_first=True, show_hidden_files=False, show_system_files=False)¶ A helper to browse the first level of a directory and pass its content to
keypirinha.Plugin.set_suggestions().Parameters: - plugin (keypirinha.Plugin) – The parent plugin of the
keypirinha.CatalogItemobjects to be created. It may be used to print error/warning messages as well. - base_dir (str) – The path of the directory to browse.
- check_base_dir (bool) – Print an error message if the directory does not
exist and returns an
keypirinha.ItemCategory.ERRORkeypirinha.CatalogItemobject in the result (the format of the returnedtupleis unchanged). - search_terms (str) – If not empty, it will be fuzzy matched against the
name of each found item (see
fuzzy_score()). If the returned score is zero, the item is not included in the returned list. If the string is empty, items will be sorted by name using thenatsortmodule. - store_score (bool) – If search_terms is not empty, the resulting score
of the call to
fuzzy_score()will be stored in thedata_bagproperty of every inserted result item. - show_dirs_first (bool) – Indicates if directories should be pushed at the top of the resulting list.
- show_hidden_files (bool) – Indicates if hidden items should included. Note that a hidden item can also be system.
- show_system_files (bool) – Indicates if system items should included. Note that a system item can also be hidden.
Returns: A tuple of 3 elements
(items, match_method, sort_method)where items is a list ofkeypirinha.CatalogItemobjects, match_method is akeypirinha.Matchvalue and sort_method is akeypirinha.Sortvalue.Return type: - plugin (keypirinha.Plugin) – The parent plugin of the
-
keypirinha_util.chardet_open(file, mode='r', buffering=-1, encoding=None, **kwargs)¶ An
open()function that tries to detect text file’s encoding.This function has the same return value, behavior and parameters than the standard
open()function except thatencodingargument is ignored. It may raise the same exceptions as well.Note
- Automatic encoding detection is bypassed if the
bflag is specified in themodeargument. - The
chardetmodule is used for the auto-detection.
- Automatic encoding detection is bypassed if the
-
keypirinha_util.chardet_slurp(file)¶ Fully extract a text file into memory after having automatically detected its encoding.
-
keypirinha_util.cmdline_quote(arg_or_list, force_quote=False)¶ Joins and quotes arguments the Windows way.
Parameters: - arg_or_list (list) – The list of arguments (strings) to join and quote. This arguments can also be a string, in which case it is handled as if it was a list with a single element.
- force_quote (bool) – Force every arguments, even those that normally would not require to be quoted (i.e.: the ones with no white space included).
Returns: The resulting string (command line) containing the quoted arguments.
Return type: Raises: TypeError– At least one of the passed arguments has an unsupported type.See also
cmdline_split()if you want to do the opposite (i.e.: to split a command line).
-
keypirinha_util.cmdline_split(cmdline)¶ Splits and unquotes (the Windows way) the given command line (string).
Returns: The split command line, a list of strings containing every argument. Return type: list Raises: OSError– The underlying call to Win32’sCommandLineToArgvWfunction failed.See also
cmdline_quote()if you want to do the opposite (i.e.: to join and quote a list of arguments).
-
keypirinha_util.execute_default_action(plugin, catalog_item, catalog_action)¶ Executes a default
keypirinha.CatalogActionusing a givenkeypirinha.CatalogItemobject. plugin is the callingkeypirinha.Pluginobject.
-
keypirinha_util.file_attributes(file, follow_link=False)¶ Fetches and returns the attributes of a given file.
If the follow_link argument is True and file is a link, the function will return the attributes of its target; even if the target is also a link file (i.e.: only one level of recursion).
Returns: Combination of attributes. Return type: FileAttr Raises: FileNotFoundError– file is not found or not accessible. Or if the link could not be resolved (in case follow_link is True).
-
keypirinha_util.fuzzy_score(search, against, apply_same_case_bonus=False)¶ Returns the matching score of a search string against another one.
If case matters, the apply_same_case_bonus argument can be set to
Trueto apply a bonus on a matching characters that have the same case. You usually do not want this though since it might feel quite unnatural to the end-user.Returns: The score is an unsigned integer. 0(zero) means no match, a value greater than zero means a match. The higher the score, the better the match is.Return type: int
-
keypirinha_util.get_clipboard()¶ Returns a string containing system’s clipboard if it contains text, or an empty string otherwise.
See also
-
keypirinha_util.kwargs_decode(encoded_string)¶ Decodes a string encoded by
kwargs_encode()and returns a dictionary.See also
-
keypirinha_util.kwargs_encode(**kwargs)¶ URL encodes passed keyword arguments into an escaped string that can be used as a target property for a
keypirinha.CatalogItemobject.Only basic types are allowed:
bool,int,floatandstr. Hint: use the unpack operator to pass a dictionary like in:kwargs_encode(**mydict)Returns: The encoded string that can be decoded by
kwargs_decode().Return type: Raises: TypeError– The type of a passed value is invalid.UnicodeEncodeError–urllib.parse.quote_plus()failed.
See also
-
keypirinha_util.raise_winerror(winerr=None, msg=None)¶ Raises
OSError(formerlyWindowsError) using the given Windows Error number. If the error number is not given,ctypes.GetLastError()is called which returns the last error code set by Windows in the calling thread. Does nothing if winerr or eventually the result ofctypes.GetLastError()is0(zero).
-
keypirinha_util.read_link(link_file)¶ Reads the properties of a Shell Link File (
.lnk).Parameters: link_file (str) – The path of the .lnkfile.Returns: A dict containing the properties: {'target': "The resolved target file; path is already expanded", 'params': "Target's parameters (may be None)", 'working_dir': "Working directory (may be None)", 'desc': "Description (may be None)", 'show_cmd': "The 'show command' value (int; can be SW_SHOWNORMAL, SW_SHOWMAXIMIZED or SW_SHOWMINIMIZED; may be None)", 'icon_location': "The icon location string that should be readable by shell_string_resource() (may be None)", 'runas': "A boolean to indicate target should be run with elevated privileges"}
Return type: dict Raises: IOError– The file could not be read or is not a link.
-
keypirinha_util.scan_directory(base_dir, name_patterns='*', flags=<ScanFlags.DEFAULT: 3>, max_level=0)¶ Walks a directory and builds a list of relative paths.
This function offers an alternative to
os.walk()or the more recentos.scandir(), that has the ability to filter the elements to find by name and/or by type, and to define how deep the scan has to be done.Parameters: - base_dir (str) – The path to the directory to scan.
- name_patterns (list) – Allows to apply one (a string can be passed) or
several filters to the name of the found elements. Allowed
wildcards are
*(zero or several unknown characters) and?(any character). If you only want to apply one filter, you may pass a string. Typical example:*.txtto list all the.txtfiles. - flags (ScanFlags) – One or a combination of flags to control scan’s behavior.
- max_level (int) – Specifies how deep the scan should be.
0(zero) means only the immediate content of the specified base_dir will be returned. A max_level of1will also include the immediate content of its sub-directories, and so on... Specify a value of-1to walk the tree completely. The maximum theorical value is0xffffffff. A negative value equals0xffffffff.
Returns: The paths (strings) of found files and/or directories. Paths are relative to base_dir. The full path of an element can be build that way:
root_dir = "c:/dir" files = keypirinha.scan_directory(root_dir) if len(files) > 0: full_path = os.path.join(root_dir, files[0])
Return type: Raises: OSError– something went wrong while trying to open the specified base_dir or during the scan.Note
Win32’s
FindFirstFileis used internally.
-
keypirinha_util.set_clipboard(text)¶ Sets the content of system’s clipboard.
See also
-
keypirinha_util.shell_execute(thing, args='', working_dir='', verb='', try_runas=True, detect_nongui=True, api_flags=None, terminal_cmd=None, show=-1)¶ Executes, opens, edits (or whatever) an application, a file, a directory, by calling Win32’s
ShellExecuteExfunction.Parameters: - thing (str) – The thing to execute/launch/edit/whatever. It can be a
file, a directory, or anything recognized by
ShellExecuteEx. - args (str) – The quoted arguments (optional). Note that a
listof arguments (strings) can be given in which casecmdline_quote()is implicitely called. - working_dir (str) – The directory to execute from. This value can be empty, in which case this function tries to automatically detect it.
- verb (str) – Specifies the action to be performed and is passed as-is to
ShellExecuteEx. This value can be empty to request default action associated with the given thing. Here is the list of the common verbs from the Microsoft’s documentation:open,edit,explore,find,printandproperties. Note that all verb are not available with all kind of thing. - try_runas (bool) – Automatically try to run with elevated permissions if
the first call to
ShellExecuteExfailed withACCESS_DENIEDerror. - detect_nongui (bool) – Automatically detect if thing is a console
application (or a link pointing to a console application). In that
case, the
terminalsetting of theexternalsection defined in the application’s configuration file will be used to launch thing. - api_flags (int) – If specified, those flags will be forwarded to
ShellExecuteEx. TheSEE_MASK_NOASYNC(0x100),SEE_MASK_FLAG_NO_UI(0x400) andSEE_MASK_INVOKEIDLIST(0xC) flags are passed if this argument isNone. SeeShellExecuteExdocumentation from Microsoft for more info. - terminal_cmd (str) – If detect_nongui is
True, this value allows to force the console emulator to use, instead of reading theterminalsetting of theexternalsection defined in the application’s configuration file. Note that, like for the args parameter, alistof arguments (strings) can be given in which casecmdline_quote()is implicitely called. - show (int) – Value directly forwarded to the
nShowparameter ofShellExecuteEx. It must be one of theSW_constants. If this value is less than zero, default will be applied (currentlySW_SHOWNORMAL).
Raises: FileNotFoundError– The thing was not found.OSError– Specified thing is a link that could not be read. OrShellExecuteExfailed with the given thing and arguments. Or an unexpected/unknown error occurred internally.
Warning
It is highly recommended to use this function instead of the standard
os.startfile()because the later internally calls theShellExecutesystem function, which is obsolete, known to be bugged and behaves incorrectly in some cases.Note
- A successful call, does not necessarily mean the item has effectively been launched/executed as expected, or that the launched process ended successfully.
- This function tries to resolve shell links for the thing and the terminal_cmd arguments. Which also mean shortucts’ arguments will be prepended, if any, to the final list of arguments.
See also
web_browser_command(), which is the preferred function to open a URL since it takes care of applying user’s preferences.- thing (str) – The thing to execute/launch/edit/whatever. It can be a
file, a directory, or anything recognized by
-
keypirinha_util.shell_known_folder_path(guid)¶ Returns the path of a Shell Known Folder according to its GUID.
Parameters: guid (str) – The GUID of the desired Known Folder. Format must be:
{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}(case-insensitive; the curly braces can be omited). The list of Known Folders is available on MSDN. Note that not all Known Folders are available on every platforms.Raises: ValueError– The specified GUID is invalid (type, format or value). Or this Known Folder is not available on this platform. Or the specified Known Folder is virtual.OSError– The Known Folder is virtual, or not available on this platform.
Note
Internally calls Win32’s
SHGetKnownFolderPath.
-
keypirinha_util.shell_resolve_exe_path(path_or_name)¶ Tries to resolve path_or_name using environment
PATHandPATHEXTvariables.path_or_name can be a path or just the name of the executable to find, in which case
PATHEXTwill be used to find a match in the directories listed in thePATHvalue.Returns
Noneif executable could not be found or if an error occurred.
-
keypirinha_util.shell_string_resource(resource_location)¶ Returns the content of a string resource from an external module (DLL) according to its location. Returns
Noneif an error occurred.Parameters: resource_location (str) – The location of the desired string. The expected format is normally “@<PE-path>,-<stringID>” but the underlying function tries to be as flexible as possible since a lot of applications and shell extensions do not strictly comply to Microsoft’s rules.
-
keypirinha_util.shell_url_scheme_to_command(url_scheme)¶ Get system’s default command line associated with the given URL scheme(s); and the location of its default icon.
Parameters: url_scheme (str) – The URL scheme name (e.g. “http”, “ftp”, “mailto”, “skype”, ...). This argument can also be an iterable of URL schemes, in which case this function iterates over the given schemes until it finds a valid associated command line. Returns: The command line associated with the scheme and the shell location string of class’ default icon. Return type: tuple See also
-
keypirinha_util.slurp_text_file(file)¶ Deprecated since version 2.5.3: Use
chardet_slurp()instead
-
keypirinha_util.web_browser_command(private_mode=None, new_window=None, url=None, execute=False)¶ A Swiss Knife function to deal with the web browser setup in Keypirinha’s global configuration (see the
web_browsersetting in the[external]section), or by default, with the system’s default web browser.This function allows to:
- Open the given URL
- Get the split command line to execute the web browser, including the given URL
- Get the split command line to execute the web browser, including a placeholder element to indicate where to insert the URL to open
All the above cases take the private_mode and new_window arguments into account. The execution flow of this function depends on the url and execute arguments only.
Parameters: - private_mode (bool) – Hint the browser you want to launch it in Private
(or Incognito) mode. By default (i.e.
None), this function will get user’s configuration, or will fall back to browser’s default behavior. Specifying a boolean value (other thanNone), will override user’s configuration. - new_window (bool) – Hint the browser you want to launch a new window. By
default (i.e.
None), this function will get user’s configuration, or will fall back to browser’s default behavior. Specifying a boolean value (other thanNone), will override user’s configuration. - url (str) –
If specified, the given URL(s) will be inserted at the right place in the command line so the caller does not have to do it manually. This is convenient since, while being uncommon, the URL(s) might have to be inserted in the command line instead of just being appended.
Tip
url can also be an iterable of strings in case several URLs are to be launched, in which case, they will be opened together if possible (i.e. using the same command line).
- execute (bool) – Only taken into account if a url is specified. If this
argument is
True, the given url will be opened usingshell_execute()and taking the private_mode and new_window arguments into account if possible. The return value is then a boolean, indicating whether or not the URL has been launched successfully.
Returns: - list
If execute is
False, returns a list of arguments that represent the command line to execute in order to launch the web web browser. In that case, url can be specified so the returned command line arguments list is ready to use. Otherwise, the returned list will contain a placeholder (%1) to indicate where to insert the URL to open. ReturnsNoneif no browser could be found.- bool
If execute is
Trueand a url is specified, this function will try to open the URL and returns a boolean to indicate whether or not the launch request is successful.
Raises: TypeError– The given url argument is invalid.