11.2.2. keypirinha_util module

The keypirinha_util module offers some utility features frequently required by the plugin developer. Reference

class keypirinha_util.FileAttr

Bases: enum.IntEnum

File attribute flags returned by file_attributes().


File is compressed.

DIR = <FileAttr.DIR: 2>

Path points to a directory.

ENCRYPTED = <FileAttr.ENCRYPTED: 1048576>

File is encrypted.

EXE = <FileAttr.EXE: 16>

Path points to an executable. Combined with FILE.


Path points to an executable. Combined with FILE and EXE.

EXE_GUI = <FileAttr.EXE_GUI: 64>

Path points to an executable. Combined with FILE and EXE.

FILE = <FileAttr.FILE: 4>

Path points to a regular file.

HIDDEN = <FileAttr.HIDDEN: 262144>

File is hidden.

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.


Path points to an existing item of an unknown type. This flag might be combined with other flags except DIR, FILE, LINK, EXE, EXE_CONSOLE and EXE_GUI.

class keypirinha_util.ScanFlags

Bases: enum.IntEnum

The flags to pass to scan_directory().


Abort if any error occurs while scanning a sub-folder


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().

  • plugin (keypirinha.Plugin) – The parent plugin of the keypirinha.CatalogItem objects 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.ERROR keypirinha.CatalogItem object in the result (the format of the returned tuple is 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 the natsort module.
  • store_score (bool) – If search_terms is not empty, the resulting score of the call to fuzzy_score() will be stored in the data_bag property 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.

A tuple of 3 elements (items, match_method, sort_method) where items is a list of keypirinha.CatalogItem objects, match_method is a keypirinha.Match value and sort_method is a keypirinha.Sort value.

Return type:


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 that encoding argument is ignored. It may raise the same exceptions as well.


  • Automatic encoding detection is bypassed if the b flag is specified in the mode argument.
  • The chardet module is used for the auto-detection.

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.

  • 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).

The resulting string (command line) containing the quoted arguments.

Return type:



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


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’s CommandLineToArgvW function 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.CatalogAction using a given keypirinha.CatalogItem object. plugin is the calling keypirinha.Plugin object.

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:FileNotFoundErrorfile 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 True to 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

Returns a string containing system’s clipboard if it contains text, or an empty string otherwise.

See also



Decodes a string encoded by kwargs_encode() and returns a dictionary.

See also



URL encodes passed keyword arguments into an escaped string that can be used as a target property for a keypirinha.CatalogItem object.

Only basic types are allowed: bool, int, float and str. Hint: use the unpack operator to pass a dictionary like in: kwargs_encode(**mydict)


The encoded string that can be decoded by kwargs_decode().

Return type:



See also


keypirinha_util.raise_winerror(winerr=None, msg=None)

Raises OSError (formerly WindowsError) 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 of ctypes.GetLastError() is 0 (zero).

Reads the properties of a Shell Link File (.lnk).

Parameters:link_file (str) – The path of the .lnk file.
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 recent os.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.

  • 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: *.txt to list all the .txt files.
  • 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 of 1 will also include the immediate content of its sub-directories, and so on... Specify a value of -1 to walk the tree completely. The maximum theorical value is 0xffffffff. A negative value equals 0xffffffff.

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:



OSError – something went wrong while trying to open the specified base_dir or during the scan.


Win32’s FindFirstFile is used internally.


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 ShellExecuteEx function.

  • 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 list of arguments (strings) can be given in which case cmdline_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, print and properties. 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 ShellExecuteEx failed with ACCESS_DENIED error.
  • detect_nongui (bool) – Automatically detect if thing is a console application (or a link pointing to a console application). In that case, the terminal setting of the external section 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. The SEE_MASK_NOASYNC (0x100), SEE_MASK_FLAG_NO_UI (0x400) and SEE_MASK_INVOKEIDLIST (0xC) flags are passed if this argument is None. See ShellExecuteEx documentation 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 the terminal setting of the external section defined in the application’s configuration file. Note that, like for the args parameter, a list of arguments (strings) can be given in which case cmdline_quote() is implicitely called.
  • show (int) – Value directly forwarded to the nShow parameter of ShellExecuteEx. It must be one of the SW_ constants. If this value is less than zero, default will be applied (currently SW_SHOWNORMAL).
  • FileNotFoundError – The thing was not found.
  • OSError – Specified thing is a link that could not be read. Or ShellExecuteEx failed with the given thing and arguments. Or an unexpected/unknown error occurred internally.


It is highly recommended to use this function instead of the standard os.startfile() because the later internally calls the ShellExecute system function, which is obsolete, known to be bugged and behaves incorrectly in some cases.


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


Returns the path of a Shell Known Folder according to its GUID.


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.

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


Internally calls Win32’s SHGetKnownFolderPath.


Tries to resolve path_or_name using environment PATH and PATHEXT variables.

path_or_name can be a path or just the name of the executable to find, in which case PATHEXT will be used to find a match in the directories listed in the PATH value.

Returns None if executable could not be found or if an error occurred.


Returns the content of a string resource from an external module (DLL) according to its location. Returns None if 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.

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



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_browser setting 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.

  • 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 than None), 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 than None), 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.


    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 using shell_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.


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. Returns None if no browser could be found.


If execute is True and 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.


TypeError – The given url argument is invalid.