gws.lib.cli¶
Utilities for command line scripts.
This package is used by the gws command line commands and by the
development and test scripts. It has no dependencies on the rest of GWS and
can be imported outside of the GWS application.
It provides:
colored console output:
cprint,info,warning,errorandfatal, which exits the script. Messages are prefixed withSCRIPT_NAMEwhen set, colors are used only on a terminal.shell commands:
runechoes and runs a command and exits on failure,execruns a command and returns its output.simple file utilities:
find_dirs,find_files,ensure_dir,read_file,write_file.a script entry point:
parse_argsparses-opt valueand--opt valuestyle arguments,mainruns a main function with them and prints the usage on-h.text_table, which formats rows as a plain text table.ProgressIndicator, a context manager that logs the progress of a long-running task in percent steps.
Example:
import gws.lib.cli as cli
USAGE = '''
Usage: myscript.py <dir> [-pattern <regex>]
'''
def main(args):
paths = list(cli.find_files(args[1], args.get('pattern')))
cli.info(cli.text_table([{'path': p} for p in paths], header='auto'))
with cli.ProgressIndicator('processing', len(paths)) as pi:
for p in paths:
pi.update()
return 0
if __name__ == '__main__':
cli.main('myscript', main, USAGE)
Source code: gws.lib.cli
Package Contents¶
- gws.lib.cli.cprint(clr, msg)¶
Print a message to stdout, in color if stdout is a terminal.
- Parameters:
clr – Color name, e.g.
redorcyan, or an empty value for no color.msg – Message.
- gws.lib.cli.ensure_dir(path)¶
Create a directory, including parent directories.
- Parameters:
path – Directory path.
- Returns:
The path.
- gws.lib.cli.error(msg)¶
Print an error message in red.
- Parameters:
msg – Message.
- gws.lib.cli.exec(cmd)¶
Run a shell command and return its output.
- Parameters:
cmd – Command string.
- Returns:
The stripped stdout of the command, or an error message if the command could not be run.
- gws.lib.cli.fatal(msg)¶
Print an error message in red and exit with code 1.
- Parameters:
msg – Message.
- gws.lib.cli.find_dirs(dirname)¶
Find the subdirectories of a directory, not recursively.
Hidden directories are skipped.
- Parameters:
dirname – Directory path.
- Yields:
Subdirectory paths. Nothing if
dirnameis not a directory.
- gws.lib.cli.find_files(dirname, pattern=None, deep=True)¶
Find files in a directory.
Hidden files and directories are skipped.
- Parameters:
dirname – Directory path.
pattern – Regular expression to search for in file paths.
deep – Search subdirectories too.
- Yields:
File paths. Nothing if
dirnameis not a directory.
- gws.lib.cli.info(msg)¶
Print an info message in cyan.
- Parameters:
msg – Message.
- gws.lib.cli.main(name, main_fn, usage)¶
Run the main function of a script.
Parses
sys.argvand callsmain_fnwith the parsed arguments. With-hor--help, prints the usage text and exits. The return value ofmain_fnis used as the exit code. Exceptions are printed as internal errors and exit with code 1, keyboard interrupts exit with code 130.- Parameters:
name – Script name, used as a prefix for messages.
main_fn – Main function, called with the dict from
parse_args.usage – Usage text.
- gws.lib.cli.parse_args(argv)¶
Parse command line arguments.
-optand--optset the optionopttoTrue, a following non-option argument sets it to that value instead. Other arguments are stored under integer keys, in order. A-argument stores all remaining arguments as a list under_rest.- Parameters:
argv – Arguments, usually
sys.argv.- Returns:
A dict of options and positional arguments.
- class gws.lib.cli.ProgressIndicator(title, total=0, resolution=10)¶
Context manager that logs the progress of a task.
Logs
STARTon enter, the progress in percent steps onupdate, andENDwith the elapsed time on a normal exit.- lastd = 0¶
- progress = 0¶
- resolution = 10¶
- starttime = 0¶
- title¶
- total = 0¶
- log(s)¶
Log a message with the title.
- Parameters:
s – Message.
- update(add=1)¶
Add processed items and log the progress if it reached the next step.
- Parameters:
add – Number of processed items.
- gws.lib.cli.read_file(path)¶
Read a text file.
- Parameters:
path – File path.
- Returns:
The file content, stripped.
- gws.lib.cli.run(cmd)¶
Print and run a shell command, exit the script if it fails.
The command output is not captured.
- Parameters:
cmd – Command as a string or a list of strings, which are joined with spaces.
- gws.lib.cli.SCRIPT_NAME = ''¶
Name of the running script, used as a prefix for messages.
- gws.lib.cli.text_table(data, header=None, delim=' | ')¶
Format rows as a plain text table.
Numbers are right-aligned, other values left-aligned.
- Parameters:
data – Rows, either dicts or sequences.
header – Column keys, or
autoto use the keys (or indexes) of the first row. If given, a header line is printed. IfNone, the columns of the first row are used without a header.delim – Column delimiter.
- Returns:
The table text, or an empty string if there are no rows.
- gws.lib.cli.warning(msg)¶
Print a warning message in yellow.
- Parameters:
msg – Message.
- gws.lib.cli.write_file(path, text)¶
Write a text file.
- Parameters:
path – File path.
text – Content.