Module commandlineopt
- exception NoTracebackError
Exception class which, when raised, shows the error message only, without traceback. Its usage requires running set_up_no_traceback_error()
- command_line_options(default_opt, help_msg='Command line usage:...', positional_keys='', synonyms={}, tolerate_extra=False, tolerated_regexp=[], warning_extra=True, advanced_help_msg={}, arglist=None, add_defaults=True)
Reads command line arguments and returns them after filling with default values
Here below, we refer to option names as keys (e.g. the “i” in “program.py -i inputfile” ), and arguments for their argument (e.g. “inputfile” above).
- Parameters:
default_opt (dict) – defines default arguments for all command lines keys. Their value types also define the typing enforced on command line arguments. Possible value types are int, float, str, bool (whose argument can be omitted), list (multiple args accepted)
help_msg (str) – if any of -h | -help | –help are provided, this help message is displayed and the script exits
positional_keys (iterable) – these keys will be associated, in order, to argumentss with no explicit keys (e.g. script.py arg1 arg2)
synonyms (dict) – add synonyms for keys; e.g. if you use {‘input’:’i’, ‘p’:’param’} then using -input or -i in the command line will be equivalent note: the built-in {‘help’:’h’} is automatically added
tolerate_extra (bool) – normally any key not found in default_opt raises an error; this allows to tolerate & accept unexpected keys
tolerated_regexp (list) – define which unexpected keys to tolerate using regexp syntax, employed by module re
warning_extra (bool) – when keys are tolerated (see two previous args), normally a warning is printed; set this to False to silence them
advanced_help_msg (dict) – dictionary defining specialized help messages, which are displayed only when invoked as argument to
-he.g. if you run on the command line `` -h map, and if within the script you had ``advanced_help_msg={'map':'map message'}, then ‘map message’ is displayed By default, the normal help_msg is also displayed before the specialized one. Add None as key to ovveride. For example,advanced_help_msg={'map':'map message', None:''}will result in only the specialized message printed when-h mapis usedarglist (list, optional) – normally options are read from sys.argv, which is automatically filled from command line arguments. Use arglist to provide an analogous list of strings instead
add_defaults (bool) – normally those options not specified on the command line are taken from def_opt. Set add_defaults=False to simply omit them from the output
- Returns:
opt – dictionary like object with structure key:arg, carrying command line options and, if not provided, default values
- Return type:
CommandLineOptions
Examples
Example 1
If you use this code in your python script:
opt=command_line_options( default_opt={'i': 'input', 'o':'output', 'param':3} )
Then, when your script is run with this command line (in bash or analogous):
script.py -i file1 -o file2
… this will result in this dictionary returned by
command_line_options:{'i':'file1', 'o':'file2', 'param':3}
Different command line and resulting dictionary returned:
script.py -i file1 -param -1
{'i':'file1', 'o':'output', 'param':-1} # note param is cast to int
Example 2
With:
opt=command_line_options( default_opt={'param':3, 'files':[]}, synonyms={'p':'param'})
This command line:
script.py -files a b c d e -p 10
Results in:
{'files':['a', 'b', 'c', 'd', 'e'], 'param':10} # note -p as synonym
Example 3
With:
opt=command_line_options( default_opt={'i':'', 'o':'', 's':'', 'k':5.5}, positional_keys=['i', 'o'])
This command line:
script.py -k 4.5 in1 out1
Results in:
{'i':'in1', 'o':'out1', 's':'', 'k':4.5} # positional args
While this command line:
script.py in1 out1 -k 10
Results in:
{'i':'in1', 'o':'out1', 's':'', 'k':10.0} # this order also accepted # note -k cast to float
And this command line:
script.py in1 -s "multi word str"
Results in:
{'i':'in1', 'o':'', 's':'multi char str', 'k':5.5} # multiword string as arg
Note that, while the object returned by command_line_options is a dictionary, it is subclassed and implements its own representation function, so that if you actually try to print it, you would get something like:
>>> print( opt ) i : str = in1 k : float = 5.5 o : str = s : str = multi char str
- read_config_file(fileh_or_path, types_from=None, sep='=', comment_char='#')
Reads parameters from a configuration file
The file is expected to have a structure like:
option_name1 = valueoption_name2 = another valueYou may specify value type (default is str) with this syntax:
option_name3 :list = element1 element2option_name4 :int = 1option_name5 :float = 0.5option_name6 :bool = FalseThe file may contain any number of empty lines and comments (i.e. lines that start with #)
This function may be used in combination with command_line_options to have different levels of default values:
built-in in your scripts
defined in (editable) configuration file
specified when running the script on the command line
Check the scripts in the templates/ folder of easyterm github for examples.
- Parameters:
fileh_or_path (file | str) – file path specification or buffer of configuration file to be loaded
types_from (dict | CommandLineOptions, optional) – If provided, this dictionary or dict-like object is used to infer the expected types of value for each key (=parameter name). Values are coerced to the type of values provided in this dictionary, and an exception is raised if conversion fails. Note: the type of the values of the types_from argument are used! Do not provide types directly as values. In a combined read_config_file / command_line_options set-up, def_opt is used here (see examples below)
sep (str) – defines which separator is used between the option_name and the value in the configuration file. Defaults to
=comment_char (str) – lines starting with this characters are ignored. Defaults to
#
- Returns:
opt – dictionary like object with structure key:arg, carrying options loaded from the file
- Return type:
CommandLineOptions
Examples
Showing the content of an example config file:
>>> for line in open('example_config.txt'): ... print(line) ## this is a config file i = inputfile o = outputfile n = 56
>>> read_config_file('example_config.txt') i : str = inputfile n : str = 56 o : str = outputfile
Using a default opt to coerce types:
>>> def_opt={'i':'inputfile', 'n':5, 'o':''} ... read_config_file('example_config.txt', types_from=def_opt) i : str = inputfile n : int = 56 o : str = outputfile
Combining read_config_file and command_line_opt
Options have built-in values (initial
def_opt). Some may be overriden by a configuration file (conf_opt). Then again, some may be overriden by command line options (opt):>>> def_opt = {'i':'inputfile', 'n':5, 'o':''} ... conf_opt = read_config_file('example_config.txt', types_from=def_opt) ... def_opt.update(conf_opt) ... opt=command_line_opt(def_opt, help_msg='Command line usage: ...')
- set_up_no_traceback_error(set_on=True)
After this, raising NoTracebackError or its subclasses results in single error line, without traceback. Under the hood, replaces sys.excepthook
- Parameters:
set_on (bool) – normally this is set to True when the module is loaded. Call this fn with set_on=False to restore the default sys.excepthook
- Returns:
None
- Return type:
None