Change several python and robot files to 110 chars
Taking advantage of current team limit of 110 chars.
Change-Id: If7ab51fe894889967b8c8bb2f2fa4664f01117d5
Signed-off-by: Michael Walsh <micwalsh@us.ibm.com>
diff --git a/lib/bmc_ssh_utils.py b/lib/bmc_ssh_utils.py
index 71e08da..f5759fe 100755
--- a/lib/bmc_ssh_utils.py
+++ b/lib/bmc_ssh_utils.py
@@ -1,8 +1,7 @@
#!/usr/bin/env python
r"""
-This module provides many valuable bmc ssh functions such as
-bmc_execute_command.
+This module provides many valuable bmc ssh functions such as bmc_execute_command.
"""
import gen_valid as gv
@@ -19,36 +18,27 @@
test_mode=None,
time_out=None):
r"""
- Run the given command in an BMC SSH session and return the stdout, stderr
- and the return code.
+ Run the given command in an BMC SSH session and return the stdout, stderr and the return code.
- This function will obtain the global values for OPENBMC_HOST,
- OPENBMC_USERNAME, etc.
+ This function will obtain the global values for OPENBMC_HOST, OPENBMC_USERNAME, etc.
Description of arguments:
- cmd_buf The command string to be run in an SSH
- session.
- print_out If this is set, this function will print
- the stdout/stderr generated by the shell
- command.
- print_err If show_err is set, this function will
- print a standardized error report if the
- shell command returns non-zero.
- ignore_err Indicates that errors encountered on the
- sshlib.execute_command are to be ignored.
- fork Indicates that sshlib.start is to be used
- rather than sshlib.execute_command.
- quiet Indicates whether this function should run
- the pissuing() function prints an
- "Issuing: <cmd string>" to stdout. This
- defaults to the global quiet value.
- test_mode If test_mode is set, this function will
- not actually run the command. This
- defaults to the global test_mode value.
- time_out The amount of time to allow for the
- execution of cmd_buf. A value of None
- means that there is no limit to how long
- the command may take.
+ cmd_buf The command string to be run in an SSH session.
+ print_out If this is set, this function will print the stdout/stderr generated by
+ the shell command.
+ print_err If show_err is set, this function will print a standardized error report
+ if the shell command returns non-zero.
+ ignore_err Indicates that errors encountered on the sshlib.execute_command are to be
+ ignored.
+ fork Indicates that sshlib.start is to be used rather than
+ sshlib.execute_command.
+ quiet Indicates whether this function should run the pissuing() function prints
+ an "Issuing: <cmd string>" to stdout. This defaults to the global quiet
+ value.
+ test_mode If test_mode is set, this function will not actually run the command.
+ This defaults to the global test_mode value.
+ time_out The amount of time to allow for the execution of cmd_buf. A value of
+ None means that there is no limit to how long the command may take.
"""
# Get global BMC variable values.
@@ -83,35 +73,27 @@
test_mode=None,
time_out=None):
r"""
- Run the given command in an OS SSH session and return the stdout, stderr
- and the return code.
+ Run the given command in an OS SSH session and return the stdout, stderr and the return code.
This function will obtain the global values for OS_HOST, OS_USERNAME, etc.
Description of arguments:
- cmd_buf The command string to be run in an SSH
- session.
- print_out If this is set, this function will print
- the stdout/stderr generated by the shell
- command.
- print_err If show_err is set, this function will
- print a standardized error report if the
- shell command returns non-zero.
- ignore_err Indicates that errors encountered on the
- sshlib.execute_command are to be ignored.
- fork Indicates that sshlib.start is to be used
- rather than sshlib.execute_command.
- quiet Indicates whether this function should run
- the pissuing() function prints an
- "Issuing: <cmd string>" to stdout. This
- defaults to the global quiet value.
- test_mode If test_mode is set, this function will
- not actually run the command. This
- defaults to the global test_mode value.
- time_out The amount of time to allow for the
- execution of cmd_buf. A value of None
- means that there is no limit to how long
- the command may take.
+ cmd_buf The command string to be run in an SSH session.
+ print_out If this is set, this function will print the stdout/stderr generated by
+ the shell command.
+ print_err If show_err is set, this function will print a standardized error report
+ if the shell command returns non-zero.
+ ignore_err Indicates that errors encountered on the sshlib.execute_command are to be
+ ignored.
+ fork Indicates that sshlib.start is to be used rather than
+ sshlib.execute_command.
+ quiet Indicates whether this function should run the pissuing() function prints
+ an "Issuing: <cmd string>" to stdout. This defaults to the global quiet
+ value.
+ test_mode If test_mode is set, this function will not actually run the command.
+ This defaults to the global test_mode value.
+ time_out The amount of time to allow for the execution of cmd_buf. A value of
+ None means that there is no limit to how long the command may take.
"""
# Get global OS variable values.
@@ -144,32 +126,25 @@
quiet=None,
test_mode=None):
r"""
- Run the given command in an XCAT SSH session and return the stdout, stderr
- and the return code.
+ Run the given command in an XCAT SSH session and return the stdout, stderr and the return code.
- This function will obtain the global values for XCAT_HOST, XCAT_USERNAME,
- etc.
+ This function will obtain the global values for XCAT_HOST, XCAT_USERNAME, etc.
Description of arguments:
- cmd_buf The command string to be run in an SSH
- session.
- print_out If this is set, this function will print
- the stdout/stderr generated by the shell
- command.
- print_err If show_err is set, this function will
- print a standardized error report if the
- shell command returns non-zero.
- ignore_err Indicates that errors encountered on the
- sshlib.execute_command are to be ignored.
- fork Indicates that sshlib.start is to be used
- rather than sshlib.execute_command.
- quiet Indicates whether this function should run
- the pissuing() function prints an
- "Issuing: <cmd string>" to stdout. This
- defaults to the global quiet value.
- test_mode If test_mode is set, this function will
- not actually run the command. This
- defaults to the global test_mode value.
+ cmd_buf The command string to be run in an SSH session.
+ print_out If this is set, this function will print the stdout/stderr generated by
+ the shell command.
+ print_err If show_err is set, this function will print a standardized error report
+ if the shell command returns non-zero.
+ ignore_err Indicates that errors encountered on the sshlib.execute_command are to be
+ ignored.
+ fork Indicates that sshlib.start is to be used rather than
+ sshlib.execute_command.
+ quiet Indicates whether this function should run the pissuing() function prints
+ an "Issuing: <cmd string>" to stdout. This defaults to the global quiet
+ value.
+ test_mode If test_mode is set, this function will not actually run the command.
+ This defaults to the global test_mode value.
"""
# Get global XCAT variable values.
@@ -204,34 +179,27 @@
quiet=None,
test_mode=None):
r"""
- Write the given command in a device SSH session and return the stdout,
- stderr and the return code.
+ Write the given command in a device SSH session and return the stdout, stderr and the return code.
This function is useful for writing to a switch.
- This function will obtain the global values for DEVICE_HOST,
- DEVICE_USERNAME, etc.
+ This function will obtain the global values for DEVICE_HOST, DEVICE_USERNAME, etc.
Description of arguments:
- cmd_buf The command string to be run in an SSH
- session.
- print_out If this is set, this function will print
- the stdout/stderr generated by the shell
- command.
- print_err If show_err is set, this function will
- print a standardized error report if the
- shell command returns non-zero.
- ignore_err Indicates that errors encountered on the
- sshlib.execute_command are to be ignored.
- fork Indicates that sshlib.start is to be used
- rather than sshlib.execute_command.
- quiet Indicates whether this function should run
- the pissuing() function prints an
- "Issuing: <cmd string>" to stdout. This
- defaults to the global quiet value.
- test_mode If test_mode is set, this function will
- not actually run the command. This
- defaults to the global test_mode value.
+ cmd_buf The command string to be run in an SSH session.
+ print_out If this is set, this function will print the stdout/stderr generated by
+ the shell command.
+ print_err If show_err is set, this function will print a standardized error report
+ if the shell command returns non-zero.
+ ignore_err Indicates that errors encountered on the sshlib.execute_command are to be
+ ignored.
+ fork Indicates that sshlib.start is to be used rather than
+ sshlib.execute_command.
+ quiet Indicates whether this function should run the pissuing() function prints
+ an "Issuing: <cmd string>" to stdout. This defaults to the global quiet
+ value.
+ test_mode If test_mode is set, this function will not actually run the command.
+ This defaults to the global test_mode value.
"""
# Get global DEVICE variable values.
diff --git a/lib/boot_data.py b/lib/boot_data.py
index 5264efb..e644166 100755
--- a/lib/boot_data.py
+++ b/lib/boot_data.py
@@ -1,8 +1,8 @@
#!/usr/bin/env python
r"""
-This module has functions to support various data structures such as the
-boot_table, valid_boot_list and boot_results_table.
+This module has functions to support various data structures such as the boot_table, valid_boot_list and
+boot_results_table.
"""
import os
@@ -23,8 +23,7 @@
import gen_cmd as gc
import var_funcs as vf
-# The code base directory will be one level up from the directory containing
-# this module.
+# The code base directory will be one level up from the directory containing this module.
code_base_dir_path = os.path.dirname(os.path.dirname(__file__)) + os.sep
@@ -33,26 +32,19 @@
r"""
Read the boot table JSON file, convert it to an object and return it.
- Note that if the user is running without a global OS_HOST robot variable
- specified, this function will remove all of the "os_" start and end state
- requirements from the JSON data.
+ Note that if the user is running without a global OS_HOST robot variable specified, this function will
+ remove all of the "os_" start and end state requirements from the JSON data.
Description of argument(s):
- file_path The path to the boot_table file. If this
- value is not specified, it will be
- obtained from the "BOOT_TABLE_PATH"
- environment variable, if set. Otherwise,
- it will default to "data/boot_table.json".
- If this value is a relative path, this
- function will use the code_base_dir_path
- as the base directory (see definition
- above).
- os_host The host name or IP address of the host
- associated with the machine being tested.
- If the user is running without an OS_HOST
- (i.e. if this argument is blank), we
- remove os starting and ending state
- requirements from the boot entries.
+ file_path The path to the boot_table file. If this value is not specified, it will
+ be obtained from the "BOOT_TABLE_PATH" environment variable, if set.
+ Otherwise, it will default to "data/boot_table.json". If this value is a
+ relative path, this function will use the code_base_dir_path as the base
+ directory (see definition above).
+ os_host The host name or IP address of the host associated with the machine being
+ tested. If the user is running without an OS_HOST (i.e. if this argument
+ is blank), we remove os starting and ending state requirements from the
+ boot entries.
"""
if file_path is None:
file_path = os.environ.get('BOOT_TABLE_PATH', 'data/boot_table.json')
@@ -70,8 +62,8 @@
boot_file = open(temp_file_path)
boot_table = json.load(boot_file, object_hook=DotDict)
- # If the user is running without an OS_HOST, we remove os starting and
- # ending state requirements from the boot entries.
+ # If the user is running without an OS_HOST, we remove os starting and ending state requirements from
+ # the boot entries.
if os_host == "":
for boot in boot_table:
state_keys = ['start', 'end']
@@ -91,12 +83,10 @@
def create_valid_boot_list(boot_table):
r"""
- Return a list of all of the valid boot types (e.g. ['REST Power On', 'REST
- Power Off', ...]).
+ Return a list of all of the valid boot types (e.g. ['REST Power On', 'REST Power Off', ...]).
Description of argument(s):
- boot_table A boot table such as is returned by the
- create_boot_table function.
+ boot_table A boot table such as is returned by the create_boot_table function.
"""
return list(boot_table.keys())
@@ -104,16 +94,15 @@
def read_boot_lists(dir_path="data/boot_lists/"):
r"""
- Read the contents of all the boot lists files found in the given boot
- lists directory and return dictionary of the lists.
+ Read the contents of all the boot lists files found in the given boot lists directory and return
+ dictionary of the lists.
- Boot lists are simply files containing a boot test name on each line.
- These files are useful for categorizing and organizing boot tests. For
- example, there may be a "Power_on" list, a "Power_off" list, etc.
+ Boot lists are simply files containing a boot test name on each line. These files are useful for
+ categorizing and organizing boot tests. For example, there may be a "Power_on" list, a "Power_off" list,
+ etc.
- The names of the boot list files will be the keys to the top level
- dictionary. Each dictionary entry is a list of all the boot tests found
- in the corresponding file.
+ The names of the boot list files will be the keys to the top level dictionary. Each dictionary entry is
+ a list of all the boot tests found in the corresponding file.
Here is an abbreviated look at the resulting boot_lists dictionary.
@@ -128,11 +117,9 @@
...
Description of argument(s):
- dir_path The path to the directory containing the
- boot list files. If this value is a
- relative path, this function will use the
- code_base_dir_path as the base directory
- (see definition above).
+ dir_path The path to the directory containing the boot list files. If this value
+ is a relative path, this function will use the code_base_dir_path as the
+ base directory (see definition above).
"""
if not dir_path.startswith("/"):
@@ -157,10 +144,9 @@
Verify that each entry in boot_list is a supported boot test.
Description of argument(s):
- boot_list An array (i.e. list) of boot test types
- (e.g. "REST Power On").
- valid_boot_types A list of valid boot types such as that
- returned by create_valid_boot_list.
+ boot_list An array (i.e. list) of boot test types (e.g. "REST Power On").
+ valid_boot_types A list of valid boot types such as that returned by
+ create_valid_boot_list.
"""
for boot_name in boot_list:
@@ -187,20 +173,15 @@
Initialize the boot results object.
Description of argument(s):
- boot_table Boot table object (see definition above).
- The boot table contains all of the valid
- boot test types. It can be created with
- the create_boot_table function.
- boot_pass An initial boot_pass value. This program
- may be called as part of a larger test
- suite. As such there may already have
- been some successful boot tests that we
- need to keep track of.
- boot_fail An initial boot_fail value. This program
- may be called as part of a larger test
- suite. As such there may already have
- been some unsuccessful boot tests that we
- need to keep track of.
+ boot_table Boot table object (see definition above). The boot table contains all of
+ the valid boot test types. It can be created with the create_boot_table
+ function.
+ boot_pass An initial boot_pass value. This program may be called as part of a
+ larger test suite. As such there may already have been some successful
+ boot tests that we need to keep track of.
+ boot_fail An initial boot_fail value. This program may be called as part of a
+ larger test suite. As such there may already have been some unsuccessful
+ boot tests that we need to keep track of.
obj_name The name of this object.
"""
@@ -217,8 +198,8 @@
'boot_test_results')
self.__boot_results.set_sum_fields(['total', 'pass', 'fail'])
self.__boot_results.set_calc_fields(['total=pass+fail'])
- # Create one row in the result table for each kind of boot test in
- # the boot_table (i.e. for all supported boot tests).
+ # Create one row in the result table for each kind of boot test in the boot_table (i.e. for all
+ # supported boot tests).
for boot_name in list(boot_table.keys()):
self.__boot_results.add_row(boot_name)
@@ -227,16 +208,14 @@
Add row to tally_sheet class object.
Description of argument(s):
- See add_row method in tally_sheet.py for a description of all
- arguments.
+ See add_row method in tally_sheet.py for a description of all arguments.
"""
self.__boot_results.add_row(*args, **kwargs)
def return_total_pass_fail(self):
r"""
- Return the total boot_pass and boot_fail values. This information is
- comprised of the pass/fail values from the table plus the initial
- pass/fail values.
+ Return the total boot_pass and boot_fail values. This information is comprised of the pass/fail
+ values from the table plus the initial pass/fail values.
"""
totals_line = self.__boot_results.calc()
@@ -248,16 +227,13 @@
boot_status):
r"""
Update our boot_results_table. This includes:
- - Updating the record for the given boot_type by incrementing the pass
- or fail field.
+ - Updating the record for the given boot_type by incrementing the pass or fail field.
- Calling the calc method to have the totals calculated.
Description of argument(s):
- boot_type The type of boot test just done (e.g.
- "REST Power On").
- boot_status The status of the boot just done. This
- should be equal to either "pass" or "fail"
- (case-insensitive).
+ boot_type The type of boot test just done (e.g. "REST Power On").
+ boot_status The status of the boot just done. This should be equal to either "pass"
+ or "fail" (case-insensitive).
"""
self.__boot_results.inc_row_field(boot_type, boot_status.lower())
@@ -269,8 +245,8 @@
String-print the formatted boot_resuls_table and return them.
Description of argument(s):
- header_footer This indicates whether a header and footer
- are to be included in the report.
+ header_footer This indicates whether a header and footer are to be included in the
+ report.
"""
buffer = ""
@@ -289,9 +265,8 @@
Description of argument(s):
See sprint_report for details.
- quiet Only print if this value is 0. This
- function will search upward in the stack
- to get the default value.
+ quiet Only print if this value is 0. This function will search upward in the
+ stack to get the default value.
"""
quiet = int(gm.dft(quiet, gp.get_stack_var('quiet', 0)))
@@ -300,8 +275,7 @@
def sprint_obj(self):
r"""
- sprint the fields of this object. This would normally be for debug
- purposes only.
+ sprint the fields of this object. This would normally be for debug purposes only.
"""
buffer = ""
@@ -316,8 +290,7 @@
def print_obj(self):
r"""
- Print the fields of this object to stdout. This would normally be for
- debug purposes.
+ Print the fields of this object to stdout. This would normally be for debug purposes.
"""
gp.gp_print(self.sprint_obj())
@@ -330,13 +303,10 @@
Create a file path to be used to store a boot_results object.
Description of argument(s):
- pgm_name The name of the program. This will form
- part of the resulting file name.
- openbmc_nickname The name of the system. This could be a
- nickname, a hostname, an IP, etc. This
- will form part of the resulting file name.
- master_pid The master process id which will form part
- of the file name.
+ pgm_name The name of the program. This will form part of the resulting file name.
+ openbmc_nickname The name of the system. This could be a nickname, a hostname, an IP,
+ etc. This will form part of the resulting file name.
+ master_pid The master process id which will form part of the file name.
"""
USER = os.environ.get("USER", "")
@@ -351,12 +321,10 @@
def cleanup_boot_results_file():
r"""
- Delete all boot results files whose corresponding pids are no longer
- active.
+ Delete all boot results files whose corresponding pids are no longer active.
"""
- # Use create_boot_results_file_path to create a globex to find all of the
- # existing boot results files.
+ # Use create_boot_results_file_path to create a globex to find all of the existing boot results files.
globex = create_boot_results_file_path("*", "*", "*")
file_list = sorted(glob.glob(globex))
for file_path in file_list:
@@ -370,16 +338,15 @@
def update_boot_history(boot_history, boot_start_message, max_boot_history=10):
r"""
- Update the boot_history list by appending the boot_start_message and by
- removing all but the last n entries.
+ Update the boot_history list by appending the boot_start_message and by removing all but the last n
+ entries.
Description of argument(s):
boot_history A list of boot start messages.
- boot_start_message This is typically a time-stamped line of
- text announcing the start of a boot test.
- max_boot_history The max number of entries to be kept in
- the boot_history list. The oldest entries
- are deleted to achieve this list size.
+ boot_start_message This is typically a time-stamped line of text announcing the start of a
+ boot test.
+ max_boot_history The max number of entries to be kept in the boot_history list. The
+ oldest entries are deleted to achieve this list size.
"""
boot_history.append(boot_start_message)
@@ -393,9 +360,8 @@
Print the last ten boots done with their time stamps.
Description of argument(s):
- quiet Only print if this value is 0. This
- function will search upward in the stack
- to get the default value.
+ quiet Only print if this value is 0. This function will search upward in the
+ stack to get the default value.
"""
quiet = int(gm.dft(quiet, gp.get_stack_var('quiet', 0)))
diff --git a/lib/call_stack.tcl b/lib/call_stack.tcl
index fe3158c..23ae17f 100755
--- a/lib/call_stack.tcl
+++ b/lib/call_stack.tcl
@@ -1,24 +1,21 @@
#!/usr/bin/wish
-# This file provides many valuable stack inquiry procedures like
-# get_file_proc_names, get_stack_var, etc..
+# This file provides many valuable stack inquiry procedures like get_file_proc_names, get_stack_var, etc..
my_source [list print.tcl]
proc get_file_proc_names { file_path { name_regex "" } } {
- # Get all proc names from the file indicated by file_path and return them
- # as a list.
+ # Get all proc names from the file indicated by file_path and return them as a list.
# Description of argument(s):
- # file_path The path to the file whose proc names are
- # to be retrieved.
- # name_regex A regular expression to be used to narrow
- # the result to just the desired procs.
+ # file_path The path to the file whose proc names are to be retrieved.
+ # name_regex A regular expression to be used to narrow the result to just the desired
+ # procs.
- # The first sed command serves to eliminate curly braces from the target
- # file. They are a distraction to what we are trying to do.
+ # The first sed command serves to eliminate curly braces from the target file. They are a distraction to
+ # what we are trying to do.
# TCL proc lines begin with...
# - Zero or more spaces...
# - The "proc" keyword...
@@ -34,14 +31,12 @@
proc get_stack_var { var_name { default {} } { init_stack_ix 1 } } {
- # Starting with the caller's stack level, search upward in the call stack,
- # for a variable named "${var_name}" and return its value. If the variable
- # cannot be found, return ${default}.
+ # Starting with the caller's stack level, search upward in the call stack, for a variable named
+ # "${var_name}" and return its value. If the variable cannot be found, return ${default}.
# Description of argument(s):
# var_name The name of the variable be searched for.
- # default The value to return if the the variable
- # cannot be found.
+ # default The value to return if the the variable cannot be found.
for {set stack_ix $init_stack_ix} {$stack_ix <= [info level]} \
{incr stack_ix} {
@@ -56,19 +51,15 @@
proc get_stack_var_level { var_name { init_stack_ix 1 } { fail_on_err 1 } } {
- # Starting with the caller's stack level, search upward in the call stack,
- # for a variable named "${var_name}" and return its associated stack level.
- # If the variable cannot be found, return -1.
+ # Starting with the caller's stack level, search upward in the call stack, for a variable named
+ # "${var_name}" and return its associated stack level. If the variable cannot be found, return -1.
# Description of argument(s):
# var_name The name of the variable be searched for.
- # init_stack_ix The level of the stack where the search
- # should start. The default is 1 which is
- # the caller's stack level.
- # fail_on_err Indicates that if the variable cannot be
- # found on the stack, this proc should write
- # to stderr and exit with a non-zero return
- # code.
+ # init_stack_ix The level of the stack where the search should start. The default is 1
+ # which is the caller's stack level.
+ # fail_on_err Indicates that if the variable cannot be found on the stack, this proc
+ # should write to stderr and exit with a non-zero return code.
for {set stack_ix $init_stack_ix} {$stack_ix <= [info level]} \
{incr stack_ix} {
@@ -91,16 +82,12 @@
proc get_stack_proc_name { { level -1 } { include_args 0 } } {
- # Get the name of the procedure at the indicated call stack level and
- # return it.
+ # Get the name of the procedure at the indicated call stack level and return it.
# Description of argument(s):
- # level The call stack level: 0 would mean this
- # procedure's level (i.e.
- # get_stack_proc_name's level), -1 would
- # indicate the caller's level, etc.
- # include_args Indicates whether proc arg values should
- # be included in the result.
+ # level The call stack level: 0 would mean this procedure's level (i.e.
+ # get_stack_proc_name's level), -1 would indicate the caller's level, etc.
+ # include_args Indicates whether proc arg values should be included in the result.
# Set default.
set_var_default level -1
@@ -127,24 +114,19 @@
# Example:
# set call_stack [get_call_stack 0]
- # call_stack: get_call_stack calc_wrap_stack_ix_adjust sprint_var
- # sprint_vars print_vars
+ # call_stack: get_call_stack calc_wrap_stack_ix_adjust sprint_var sprint_vars print_vars
# Description of argument(s):
- # stack_top_ix The index to the bottom of the stack to be
- # returned. 0 means include the entire
- # stack. 1 means include the entire stack
- # with the exception of this procedure
- # itself, etc.
- # include_args Indicates whether proc args should be
- # included in the result.
+ # stack_top_ix The index to the bottom of the stack to be returned. 0 means include the
+ # entire stack. 1 means include the entire stack with the exception of
+ # this procedure itself, etc.
+ # include_args Indicates whether proc args should be included in the result.
set_var_default stack_top_ix -1
# Get the current stack size.
set stack_size [info level]
- # Calculate stack_bottom_ix. Example: if stack_size is 5, stack_bottom_ix
- # is -4.
+ # Calculate stack_bottom_ix. Example: if stack_size is 5, stack_bottom_ix is -4.
set stack_bottom_ix [expr 1 - $stack_size]
for {set stack_ix $stack_top_ix} {$stack_ix >= $stack_bottom_ix} \
{incr stack_ix -1} {
diff --git a/lib/cmd.tcl b/lib/cmd.tcl
index a41fcf4..f9865d0 100755
--- a/lib/cmd.tcl
+++ b/lib/cmd.tcl
@@ -8,8 +8,7 @@
proc cmd_fnc { cmd_buf { quiet {} } { test_mode {} } { print_output {} }\
{ show_err {} } { ignore_err {} } { acceptable_shell_rcs {} } } {
- # Run the given command in a shell and return the shell return code and the
- # output as a 2 element list.
+ # Run the given command in a shell and return the shell return code and the output as a 2 element list.
# Example usage:
# set result [cmd_fnc "date"].
@@ -20,42 +19,30 @@
# Mon Feb 19 10:12:10 CST 2018
# result:
# result[0]: 0x00000000
- # result[1]: Mon Feb 19 10:12:10 CST
- # 2018
+ # result[1]: Mon Feb 19 10:12:10 CST 2018
- # Note: Because of the way this procedure processes parms, the user can
- # specify blank values as a way of skipping parms. In the following
- # example, the caller is indicating that they wish to have quiet and
+ # Note: Because of the way this procedure processes parms, the user can specify blank values as a way of
+ # skipping parms. In the following example, the caller is indicating that they wish to have quiet and
# test_mode take their normal defaults but have print_output be 0.:
# cmd_fnc "date" "" "" 0
# Description of argument(s):
# cmd_buf The command string to be run in a shell.
- # quiet Indicates whether this procedure should
- # run the print_issuing() procedure which
- # prints "Issuing: <cmd string>" to stdout.
- # The default value is 0.
- # test_mode If test_mode is set, this procedure will
- # not actually run the command. If
- # print_output is set, it will print
- # "(test_mode) Issuing: <cmd string>" to
- # stdout. The default value is 0.
- # print_output If this is set, this procedure will print
- # the stdout/stderr generated by the shell
- # command. The default value is 1.
- # show_err If show_err is set, this procedure will
- # print a standardized error report if the
- # shell command returns non-zero. The
- # default value is 1.
- # ignore_err If ignore_err is set, this procedure will
- # not fail if the shell command fails.
- # However, if ignore_err is not set, this
- # procedure will exit 1 if the shell command
- # fails. The default value is 1.
- # acceptable_shell_rcs A list of acceptable shell rcs. If the
- # shell return code is found in this list,
- # the shell command is considered
- # successful. The default value is {0}.
+ # quiet Indicates whether this procedure should run the print_issuing() procedure
+ # which prints "Issuing: <cmd string>" to stdout. The default value is 0.
+ # test_mode If test_mode is set, this procedure will not actually run the command.
+ # If print_output is set, it will print "(test_mode) Issuing: <cmd string>"
+ # to stdout. The default value is 0.
+ # print_output If this is set, this procedure will print the stdout/stderr generated by
+ # the shell command. The default value is 1.
+ # show_err If show_err is set, this procedure will print a standardized error report
+ # if the shell command returns non-zero. The default value is 1.
+ # ignore_err If ignore_err is set, this procedure will not fail if the shell command
+ # fails. However, if ignore_err is not set, this procedure will exit 1 if
+ # the shell command fails. The default value is 1.
+ # acceptable_shell_rcs A list of acceptable shell rcs. If the shell return code is found in
+ # this list, the shell command is considered successful. The default value
+ # is {0}.
# Set defaults.
set_var_default quiet [get_stack_var quiet 0 2]
@@ -84,8 +71,7 @@
append error_message "The prior shell command failed.\n"
append error_message [sprint_var shell_rc "" "" 1]
if { $acceptable_shell_rcs != 0 } {
- # acceptable_shell_rcs contains more than just a single element equal
- # to 0.
+ # acceptable_shell_rcs contains more than just a single element equal to 0.
append error_message "\n"
append error_message [sprint_list acceptable_shell_rcs "" "" 1]
}
@@ -109,28 +95,24 @@
proc t_cmd_fnc { args } {
- # Call cmd_fnc with test_mode equal to the test_mode setting found by
- # searching up the call stack. See cmd_fnc (above) for details for all
- # other arguments.
+ # Call cmd_fnc with test_mode equal to the test_mode setting found by searching up the call stack. See
+ # cmd_fnc (above) for details for all other arguments.
- # We wish to obtain a value for test_mode by searching up the call stack.
- # This value will govern whether the command specified actually gets
- # executed.
+ # We wish to obtain a value for test_mode by searching up the call stack. This value will govern whether
+ # the command specified actually gets executed.
set_var_default test_mode [get_stack_var test_mode 0 2]
- # Since we wish to manipulate the value of test_mode, which is the third
- # positional parm, we must make sure we have at least 3 parms. We will now
- # append blank values to the args list as needed to ensure that we have the
- # minimum 3 parms.
+ # Since we wish to manipulate the value of test_mode, which is the third positional parm, we must make
+ # sure we have at least 3 parms. We will now append blank values to the args list as needed to ensure that
+ # we have the minimum 3 parms.
set min_args 3
for {set ix [llength $args]} {$ix < $min_args} {incr ix} {
lappend args {}
}
- # Now replace the caller's test_mode value with the value obtained from the
- # call stack search. It does not matter what value is specified by the
- # caller for test_mode. It will be replaced. The whole point of calling
- # t_cmd_fnc is to allow it to set the test_mode.
+ # Now replace the caller's test_mode value with the value obtained from the call stack search. It does
+ # not matter what value is specified by the caller for test_mode. It will be replaced. The whole point of
+ # calling t_cmd_fnc is to allow it to set the test_mode.
set args [lreplace $args 2 2 $test_mode]
return [cmd_fnc {*}$args]
diff --git a/lib/data_proc.tcl b/lib/data_proc.tcl
index c446693..e6324c0 100755
--- a/lib/data_proc.tcl
+++ b/lib/data_proc.tcl
@@ -1,18 +1,15 @@
#!/usr/bin/wish
-# This file provides many valuable data processing procedures like
-# lappend_unique, get_var, etc.
+# This file provides many valuable data processing procedures like lappend_unique, get_var, etc.
proc lappend_unique { args } {
- # Add the each entry to a list if and only if they do not already exist in
- # the list.
+ # Add the each entry to a list if and only if they do not already exist in the list.
# Description of argument(s):
- # args The first argument should be the list
- # name. All other arguments are items to be
- # added to the list.
+ # args The first argument should be the list name. All other arguments are
+ # items to be added to the list.
set list_name [lindex $args 0]
# Remove first entry from args list.
@@ -37,11 +34,9 @@
# Description of argument(s):
# main_list_name The name of your master list.
- # removal_list The list of items to be removed from
- # master list.
+ # removal_list The list of items to be removed from master list.
- # For each element in the removal list, find the corresponding entry in the
- # master list and remove it.
+ # For each element in the removal list, find the corresponding entry in the master list and remove it.
for {set removal_ix 0} {$removal_ix < [llength $removal_list ]}\
{incr removal_ix} {
set value [lindex $removal_list $removal_ix]
@@ -54,15 +49,13 @@
proc list_map { list expression } {
- # Create and return a new list where each element of the new list is a
- # result of running the given expression on the corresponding entry from the
- # original list.
+ # Create and return a new list where each element of the new list is a result of running the given
+ # expression on the corresponding entry from the original list.
# Description of argument(s):
# list A list to be operated on.
- # expression A command expression to be run on each
- # element in the list (e.g. '[string range
- # $x 1 end]').
+ # expression A command expression to be run on each element in the list (e.g. '[string
+ # range $x 1 end]').
foreach x $list {
set cmd_buf "lappend new_list ${expression}"
@@ -76,15 +69,14 @@
proc list_filter { list expression } {
- # Create and return a new list consisting of all elements of the original
- # list that do NOT pass the expression.
+ # Create and return a new list consisting of all elements of the original list that do NOT pass the
+ # expression.
# Description of argument(s):
# list A list to be operated on.
- # expression A command expression to be run on each
- # element in the list (e.g. 'regexp
- # -expanded {^[[:blank:]]*\#|^[[:blank:]]*$}
- # $x', 'string equal $x ""', etc.).
+ # expression A command expression to be run on each element in the list (e.g. 'regexp
+ # -expanded {^[[:blank:]]*\#|^[[:blank:]]*$} $x', 'string equal $x ""',
+ # etc.).
set new_list {}
@@ -118,17 +110,15 @@
proc get_var { var_var { default ""} } {
upvar 1 $var_var var_ref
- # Return the value of the variable expression or the value of default if
- # the variable is not defined.
+ # Return the value of the variable expression or the value of default if the variable is not defined.
# Example use:
# set PATH [get_var ::env(PATH) "/usr/bin"]
# Description of argument(s):
- # var_var The name of a variable (e.g.
- # "::env(NANOSECOND)" or "var1").
- # default The default value to return if the
- # variable named in var_var does not exist.
+ # var_var The name of a variable (e.g. "::env(NANOSECOND)" or "var1").
+ # default The default value to return if the variable named in var_var does not
+ # exist.
expr { [info exists var_ref] ? [return $var_ref] : [return $default] }
@@ -138,17 +128,15 @@
proc set_var_default { var_name { default ""} } {
upvar 1 $var_name var_ref
- # If the variable named in var_name is either blank or non-existent, set
- # its value to the default.
+ # If the variable named in var_name is either blank or non-existent, set its value to the default.
# Example use:
# set_var_default indent 0
# Description of argument(s):
# var_name The name of a variable.
- # default The default value to assign to the
- # variable if the variable named in var_name
- # is blank or non-existent.
+ # default The default value to assign to the variable if the variable named in
+ # var_name is blank or non-existent.
if { ! ([info exists var_ref] && $var_ref != "") } {
set var_ref $default
@@ -161,16 +149,13 @@
upvar $dir_path ref_dir_path
upvar $base_name ref_base_name
- # Split a path into it's dir_path and base_name. The dir_path variable
- # will include a trailing slash.
+ # Split a path into it's dir_path and base_name. The dir_path variable will include a trailing slash.
# Description of argument(s):
# path The directory or file path.
- # dir_path The variable to contain the resulting
- # directory path which will include a
+ # dir_path The variable to contain the resulting directory path which will include a
# trailing slash.
- # base_name The variable to contain the resulting base
- # directory or file name.
+ # base_name The variable to contain the resulting base directory or file name.
set ref_dir_path "[file dirname ${path}]/"
set ref_base_name "[file tail $path]"
@@ -187,15 +172,13 @@
# The properties file must have the following format:
# var_name=var_value
- # Comment lines (those beginning with a "#") and blank lines are allowed
- # and will be ignored. Leading and trailing single or double quotes will be
- # stripped from the value. E.g.
+ # Comment lines (those beginning with a "#") and blank lines are allowed and will be ignored. Leading and
+ # trailing single or double quotes will be stripped from the value. E.g.
# var1="This one"
# Quotes are stripped so the resulting value for var1 is:
# This one
- # Suggestion: The caller can then process the result as an array or a
- # dictionary.
+ # Suggestion: The caller can then process the result as an array or a dictionary.
# Example usage:
@@ -240,8 +223,7 @@
proc convert_array_key {key {convert_commands} {prefix ""} } {
- # Convert the key according to the caller's convert_commands and return the
- # result.
+ # Convert the key according to the caller's convert_commands and return the result.
# This is designed as a helper procedure to be called by convert_array_keys.
@@ -273,35 +255,26 @@
upvar $source_arr source_arr_ref
upvar $target_arr target_arr_ref
- # Convert the keys of source_arr according to the caller's convert_commands
- # and put the resulting array in target_arr. If this procedure fails for any
- # reason, it will return non-zero.
+ # Convert the keys of source_arr according to the caller's convert_commands and put the resulting array in
+ # target_arr. If this procedure fails for any reason, it will return non-zero.
- # Note that despite the name of this procedure, it will also work on a
- # dictionary. In other words, if source_arr is NOT an array, it will be
- # processed as a dictionary and target_arr will be created as a dictionary
- # as well.
+ # Note that despite the name of this procedure, it will also work on a dictionary. In other words, if
+ # source_arr is NOT an array, it will be processed as a dictionary and target_arr will be created as a
+ # dictionary as well.
# Description of argument(s):
# source_arr The source array that is to be converted.
- # target_arr The target array that results from the
- # conversion.
- # convert_commands A list of custom commands that indicate
- # the type of conversion(s) the caller
- # wishes to see. Currently the accepted
- # values are as follows:
- # upper Convert key value to uppercase.
- # lower Convert key value to lowercase.
- # prefix Prepend prefix to the key, provided that
- # it does not already exist. If upper or
- # lower is included in convert_commands
- # list, the prefix will be converted to the
- # specified case as well.
- # rm_prefix Remove a prefix that is prepended,
- # provided that it exists.
- # prefix The prefix to be used for "prefix" and
- # "rm_prefix" commands (see convert_commands
- # text above).
+ # target_arr The target array that results from the conversion.
+ # convert_commands A list of custom commands that indicate the type of conversion(s) the
+ # caller wishes to see. Currently the accepted values are as follows:
+ # upper Convert key value to uppercase.
+ # lower Convert key value to lowercase.
+ # prefix Prepend prefix to the key, provided that it does not already exist. If
+ # upper or lower is included in convert_commands list, the prefix will be
+ # converted to the specified case as well.
+ # rm_prefix Remove a prefix that is prepended, provided that it exists.
+ # prefix The prefix to be used for "prefix" and "rm_prefix" commands (see
+ # convert_commands text above).
# Validate arguments.
if { [lsearch $convert_commands lower] != -1 } {
@@ -343,8 +316,7 @@
} else {
# Initialize targ dictionary.
set target_arr_ref [list]
- # Walk the source dictionary doing the conversion specified in
- # convert_commands.
+ # Walk the source dictionary doing the conversion specified in convert_commands.
foreach {key value} $source_arr_ref {
set new_key [convert_array_key $key $convert_commands $prefix]
set cmd_buf "dict append target_arr_ref $new_key \$value"
@@ -358,8 +330,8 @@
proc expand_shell_string {buffer} {
upvar $buffer ref_buffer
- # Call upon the shell to expand the string in "buffer", i.e. the shell will
- # make substitutions for environment variables and glob expressions.
+ # Call upon the shell to expand the string in "buffer", i.e. the shell will make substitutions for
+ # environment variables and glob expressions.
# Description of argument(s):
# buffer The buffer to be expanded.
@@ -367,8 +339,8 @@
# This is done to keep echo from interpreting all of the double quotes away.
regsub -all {\"} $ref_buffer "\\\"" ref_buffer
- # Bash will compress extra space delimiters if you don't quote the string.
- # So, we quote the argument to echo.
+ # Bash will compress extra space delimiters if you don't quote the string. So, we quote the argument to
+ # echo.
if {[catch {set ref_buffer [exec bash -c "echo \"$ref_buffer\""]} result]} {
puts stderr $result
exit 1
@@ -380,13 +352,11 @@
proc add_trailing_string { buffer { add_string "/" } } {
upvar $buffer ref_buffer
- # Add the add string to the end of the buffer if and only if it doesn't
- # already end with the add_string.
+ # Add the add string to the end of the buffer if and only if it doesn't already end with the add_string.
# Description of argument(s):
# buffer The buffer to be modified.
- # add_string The string to conditionally append to the
- # buffer.
+ # add_string The string to conditionally append to the buffer.
regsub -all "${add_string}$" $ref_buffer {} ref_buffer
set ref_buffer "${ref_buffer}${add_string}"
diff --git a/lib/escape.tcl b/lib/escape.tcl
index 493d943..e854792 100755
--- a/lib/escape.tcl
+++ b/lib/escape.tcl
@@ -1,16 +1,13 @@
#!/usr/bin/wish
-# This file provides many valuable quote and metachar escape processing
-# procedures.
+# This file provides many valuable quote and metachar escape processing procedures.
proc escape_bash_quotes { buffer } {
- # Do a bash-style escape of all single quotes in the buffer and return the
- # result.
+ # Do a bash-style escape of all single quotes in the buffer and return the result.
- # In bash, if you wish to have a single quote (i.e. apostrophe) inside
- # single quotes, you must escape it.
+ # In bash, if you wish to have a single quote (i.e. apostrophe) inside single quotes, you must escape it.
# For example, the following bash command:
# echo 'Mike'\''s dog'
@@ -23,8 +20,7 @@
# Mike'\''s dog
# Description of argument(s):
- # buffer The string whose single quotes are to be
- # escaped.
+ # buffer The string whose single quotes are to be escaped.
regsub -all {'} $buffer {'\''} new_buffer
return $new_buffer
@@ -34,17 +30,14 @@
proc quotes_to_curly_braces { buffer } {
- # Convert a single-quoted string to a curly brace-quoted string and return
- # the result.
+ # Convert a single-quoted string to a curly brace-quoted string and return the result.
- # This procedure can help in converting bash expressions, which are quoted
- # with single quotes, to equivalent TCL expressions which are quoted with
- # curly braces. This procedure will recognize and preserve a bash single
- # quote escape sequence: '\''
+ # This procedure can help in converting bash expressions, which are quoted with single quotes, to
+ # equivalent TCL expressions which are quoted with curly braces. This procedure will recognize and
+ # preserve a bash single quote escape sequence: '\''
# Description of argument(s):
- # buffer The string whose quotes are to be
- # converted to curly braces.
+ # buffer The string whose quotes are to be converted to curly braces.
# For example, the following code...
@@ -63,8 +56,7 @@
set inside_quotes 0
- # In a bash string "'\''" is an escaped quote which we wish to convert to a
- # single quote.
+ # In a bash string "'\''" is an escaped quote which we wish to convert to a single quote.
set place_holder {supercaliforniaplace_holder}
regsub -all {'\\''} $buffer ${place_holder} buffer
@@ -72,17 +64,15 @@
for {set ix 0} {$ix < [string length $buffer]} {incr ix} {
set char [string index $buffer $ix]
if { $char == $quote } {
- # Processing a quote. inside_quotes will tell us whether we've come
- # across a left quote or a right quote.
+ # Processing a quote. inside_quotes will tell us whether we've come across a left quote or a right
+ # quote.
if { $inside_quotes == 0 } {
- # Processing closing quote. Add a left curly brace to return_buffer
- # and discard the quote char.
+ # Processing closing quote. Add a left curly brace to return_buffer and discard the quote char.
set return_buffer "${return_buffer}\{"
# Set inside_quotes to indicate we are now waiting for a closing quote.
set inside_quotes 1
} else {
- # Processing opening quote. Add a right curly brace to return_buffer
- # and discard the quote char.
+ # Processing opening quote. Add a right curly brace to return_buffer and discard the quote char.
set return_buffer "${return_buffer}\}"
# Clear inside_quotes to indicate we have found our closing quote.
set inside_quotes 0
@@ -102,17 +92,14 @@
proc curly_braces_to_quotes { buffer } {
- # Convert a curly brace-quoted string to a single-quoted string and return
- # the result.
+ # Convert a curly brace-quoted string to a single-quoted string and return the result.
- # This procedure can help in converting TCL expressions, which are quoted
- # with curly braces, to equivalent bash expressions which are quoted with
- # single quotes. This procedure will first convert single quotes to the
- # bash escaped single quote sequence: '\''
+ # This procedure can help in converting TCL expressions, which are quoted with curly braces, to equivalent
+ # bash expressions which are quoted with single quotes. This procedure will first convert single quotes to
+ # the bash escaped single quote sequence: '\''
# Description of argument(s):
- # buffer The string whose curly braces are to be
- # converted to single quotes.
+ # buffer The string whose curly braces are to be converted to single quotes.
# For example, the following buffer value:
# echo {Mike's dog}
diff --git a/lib/func_args.py b/lib/func_args.py
index 8f3f539..bc1bb7e 100644
--- a/lib/func_args.py
+++ b/lib/func_args.py
@@ -10,15 +10,13 @@
def pop_arg(default=None, *args, **kwargs):
r"""
- Pop a named argument from the args/kwargs and return a tuple consisting of
- the argument value, the modified args and the modified kwargs.
+ Pop a named argument from the args/kwargs and return a tuple consisting of the argument value, the
+ modified args and the modified kwargs.
- The name of the argument is determined automatically by this function by
- examining the source code which calls it (see examples below). If no
- suitable argument can be found, the default value passed to this function
- will be returned as the argument value. This function is useful for
- wrapper functions that wish to process arguments in some way before
- calling subordinate function.
+ The name of the argument is determined automatically by this function by examining the source code which
+ calls it (see examples below). If no suitable argument can be found, the default value passed to this
+ function will be returned as the argument value. This function is useful for wrapper functions that wish
+ to process arguments in some way before calling subordinate function.
Examples:
@@ -37,24 +35,20 @@
'Johnson', [], {'ssn': "111-11-1111"}
- Notice that the 'args' value returned is an empty list. Since last_name
- was assumed to be the first positional argument, it was popped from args.
+ Notice that the 'args' value returned is an empty list. Since last_name was assumed to be the first
+ positional argument, it was popped from args.
Now consider this call to func1:
func1(last_name='Johnson', ssn='111-11-1111')
- The pop_arg in func1 would return the same last_name value as in the
- previous example. The only difference being that the last_name value was
- popped from kwargs rather than from args.
+ The pop_arg in func1 would return the same last_name value as in the previous example. The only
+ difference being that the last_name value was popped from kwargs rather than from args.
Description of argument(s):
- default The value to return if the named argument
- is not present in args/kwargs.
- args The positional arguments passed to the
- calling function.
- kwargs The keyword arguments passed to the
- calling function.
+ default The value to return if the named argument is not present in args/kwargs.
+ args The positional arguments passed to the calling function.
+ kwargs The keyword arguments passed to the calling function.
"""
# Retrieve the argument name by examining the source code.
@@ -74,19 +68,18 @@
def source_to_object(value):
r"""
- Evaluate string value as python source code and return the resulting
- object.
+ Evaluate string value as python source code and return the resulting object.
- If value is NOT a string or can not be interpreted as a python source
- object definition, simply return value.
+ If value is NOT a string or can not be interpreted as a python source object definition, simply return
+ value.
- The idea is to convert python object definition source code (e.g. for
- lists, dictionaries, tuples, etc.) into an object.
+ The idea is to convert python object definition source code (e.g. for lists, dictionaries, tuples, etc.)
+ into an object.
Example:
- Note that this first example is a special case in that it is a short-cut
- for specifying a collections.OrderedDict.
+ Note that this first example is a special case in that it is a short-cut for specifying a
+ collections.OrderedDict.
result = source_to_object("[('one', 1), ('two', 2), ('three', 3)]")
@@ -104,8 +97,8 @@
('two', 2),
('three', 3)])")
- Also note that support for this special-case short-cut precludes the
- possibility of interpreting such a string as a list of tuples.
+ Also note that support for this special-case short-cut precludes the possibility of interpreting such a
+ string as a list of tuples.
Example:
@@ -120,8 +113,7 @@
Example:
- In this example, the value passed to this function is not a string, so it
- is simply returned.
+ In this example, the value passed to this function is not a string, so it is simply returned.
result = source_to_object(1)
@@ -132,22 +124,18 @@
etc.
Description of argument(s):
- value If value is a string, it will be evaluated
- as a python statement. If the statement
- is valid, the resulting object will be
- returned. In all other cases, the value
- will simply be returned.
+ value If value is a string, it will be evaluated as a python statement. If the
+ statement is valid, the resulting object will be returned. In all other
+ cases, the value will simply be returned.
"""
if type(value) not in gp.get_string_types():
return value
- # Strip white space prior to attempting to interpret the string as python
- # code.
+ # Strip white space prior to attempting to interpret the string as python code.
value = value.strip()
- # Try special case of collections.OrderedDict which accepts a list of
- # tuple pairs.
+ # Try special case of collections.OrderedDict which accepts a list of tuple pairs.
if value.startswith("[("):
try:
return eval("collections.OrderedDict(" + value + ")")
@@ -167,9 +155,8 @@
Run source_to_object() on each element in args and return the result.
Description of argument(s):
- args A type of dictionary, list, set, tuple or
- simple object whose elements are to be
- converted via a call to source_to_object().
+ args A type of dictionary, list, set, tuple or simple object whose elements
+ are to be converted via a call to source_to_object().
"""
type_of_dict = gp.is_dict(args)
diff --git a/lib/func_timer.py b/lib/func_timer.py
index 1919c3e..27cfa52 100644
--- a/lib/func_timer.py
+++ b/lib/func_timer.py
@@ -17,19 +17,17 @@
r"""
Define the func timer class.
- A func timer object can be used to run any function/arguments but with an
- additional benefit of being able to specify a time_out value. If the
- function fails to complete before the timer expires, a ValueError
- exception will be raised along with a detailed error message.
+ A func timer object can be used to run any function/arguments but with an additional benefit of being
+ able to specify a time_out value. If the function fails to complete before the timer expires, a
+ ValueError exception will be raised along with a detailed error message.
Example code:
func_timer = func_timer_class()
func_timer.run(run_key, "sleep 2", time_out=1)
- In this example, the run_key function is being run by the func_timer
- object with a time_out value of 1 second. "sleep 2" is a positional parm
- for the run_key function.
+ In this example, the run_key function is being run by the func_timer object with a time_out value of 1
+ second. "sleep 2" is a positional parm for the run_key function.
"""
def __init__(self,
@@ -40,8 +38,7 @@
self.__func = None
self.__time_out = None
self.__child_pid = 0
- # Save the original SIGUSR1 handler for later restoration by this
- # class' methods.
+ # Save the original SIGUSR1 handler for later restoration by this class' methods.
self.__original_SIGUSR1_handler = signal.getsignal(signal.SIGUSR1)
def __del__(self):
@@ -49,8 +46,7 @@
def sprint_obj(self):
r"""
- sprint the fields of this object. This would normally be for debug
- purposes.
+ sprint the fields of this object. This would normally be for debug purposes.
"""
buffer = ""
@@ -70,8 +66,7 @@
def print_obj(self):
r"""
- print the fields of this object to stdout. This would normally be for
- debug purposes.
+ print the fields of this object to stdout. This would normally be for debug purposes.
"""
sys.stdout.write(self.sprint_obj())
@@ -85,18 +80,14 @@
gp.lprint_executing()
gp.lprint_var(self.__child_pid)
except (AttributeError, KeyError, TypeError):
- # NOTE: In python 3, this code fails with "KeyError:
- # ('__main__',)" when calling functions like lprint_executing that
- # use inspect.stack() during object destruction. No fixes found
- # so tolerating the error. In python 2.x, it may fail with
- # TypeError. This seems to happen when cleaning up after an
- # exception was raised.
+ # NOTE: In python 3, this code fails with "KeyError: ('__main__',)" when calling functions like
+ # lprint_executing that use inspect.stack() during object destruction. No fixes found so
+ # tolerating the error. In python 2.x, it may fail with TypeError. This seems to happen when
+ # cleaning up after an exception was raised.
pass
- # If self.__child_pid is 0, then we are either running as the child
- # or we've already cleaned up.
- # If self.__time_out is None, then no child process would have been
- # spawned.
+ # If self.__child_pid is 0, then we are either running as the child or we've already cleaned up.
+ # If self.__time_out is None, then no child process would have been spawned.
if self.__child_pid == 0 or self.__time_out is None:
return
@@ -123,14 +114,11 @@
signal_number,
frame):
r"""
- Handle a SIGUSR1 generated by the child process after the time_out has
- expired.
+ Handle a SIGUSR1 generated by the child process after the time_out has expired.
- signal_number The signal_number of the signal causing
- this method to get invoked. This should
- always be 10 (SIGUSR1).
- frame The stack frame associated with the
- function that times out.
+ signal_number The signal_number of the signal causing this method to get invoked. This
+ should always be 10 (SIGUSR1).
+ frame The stack frame associated with the function that times out.
"""
gp.lprint_executing()
@@ -149,16 +137,13 @@
def run(self, func, *args, **kwargs):
r"""
- Run the indicated function with the given args and kwargs and return
- the value that the function returns. If the time_out value expires,
- raise a ValueError exception with a detailed error message.
+ Run the indicated function with the given args and kwargs and return the value that the function
+ returns. If the time_out value expires, raise a ValueError exception with a detailed error message.
- This method passes all of the args and kwargs directly to the child
- function with the following important exception: If kwargs contains a
- 'time_out' value, it will be used to set the func timer object's
- time_out value and then the kwargs['time_out'] entry will be removed.
- If the time-out expires before the function finishes running, this
- method will raise a ValueError.
+ This method passes all of the args and kwargs directly to the child function with the following
+ important exception: If kwargs contains a 'time_out' value, it will be used to set the func timer
+ object's time_out value and then the kwargs['time_out'] entry will be removed. If the time-out
+ expires before the function finishes running, this method will raise a ValueError.
Example:
func_timer = func_timer_class()
@@ -173,12 +158,9 @@
Description of argument(s):
func The function object which is to be called.
- args The arguments which are to be passed to
- the function object.
- kwargs The keyword arguments which are to be
- passed to the function object. As noted
- above, kwargs['time_out'] will get special
- treatment.
+ args The arguments which are to be passed to the function object.
+ kwargs The keyword arguments which are to be passed to the function object. As
+ noted above, kwargs['time_out'] will get special treatment.
"""
gp.lprint_executing()
@@ -186,8 +168,8 @@
# Store method parms as object parms.
self.__func = func
- # Get self.__time_out value from kwargs. If kwargs['time_out'] is
- # not present, self.__time_out will default to None.
+ # Get self.__time_out value from kwargs. If kwargs['time_out'] is not present, self.__time_out will
+ # default to None.
self.__time_out = None
if 'time_out' in kwargs:
self.__time_out = kwargs['time_out']
@@ -211,8 +193,7 @@
gp.lprint_varx("time_out", self.__time_out)
self.__child_pid = 0
if self.__time_out is not None:
- # Save the original SIGUSR1 handler for later restoration by this
- # class' methods.
+ # Save the original SIGUSR1 handler for later restoration by this class' methods.
self.__original_SIGUSR1_handler = signal.getsignal(signal.SIGUSR1)
# Designate a SIGUSR1 handling function.
signal.signal(signal.SIGUSR1, self.timed_out)
@@ -238,8 +219,8 @@
try:
result = func(*args, **kwargs)
except Exception as func_exception:
- # We must handle all exceptions so that we have the chance to
- # cleanup before re-raising the exception.
+ # We must handle all exceptions so that we have the chance to cleanup before re-raising the
+ # exception.
gp.lprint_timen("Encountered exception in user's function.")
self.cleanup()
raise(func_exception)
diff --git a/lib/gen_arg.py b/lib/gen_arg.py
index d8363c3..529cd97 100755
--- a/lib/gen_arg.py
+++ b/lib/gen_arg.py
@@ -1,8 +1,7 @@
#!/usr/bin/env python
r"""
-This module provides valuable argument processing functions like
-gen_get_options and sprint_args.
+This module provides valuable argument processing functions like gen_get_options and sprint_args.
"""
import sys
@@ -23,9 +22,9 @@
def gen_get_options(parser,
stock_list=[]):
r"""
- Parse the command line arguments using the parser object passed and return
- True/False (i.e. pass/fail). However, if gv.exit_on_error is set, simply
- exit the program on failure. Also set the following built in values:
+ Parse the command line arguments using the parser object passed and return True/False (i.e. pass/fail).
+ However, if gv.exit_on_error is set, simply exit the program on failure. Also set the following built in
+ values:
__builtin__.quiet This value is used by the qprint functions.
__builtin__.test_mode This value is used by command processing functions.
@@ -34,18 +33,13 @@
__builtin__.parser This value is used by print_program_header, etc.
Description of arguments:
- parser A parser object. See argparse module
- documentation for details.
- stock_list The caller can use this parameter to
- request certain stock parameters offered
- by this function. For example, this
- function will define a "quiet" option upon
- request. This includes stop help text and
- parm checking. The stock_list is a list
- of tuples each of which consists of an
- arg_name and a default value. Example:
- stock_list = [("test_mode", 0), ("quiet",
- 1), ("debug", 0)]
+ parser A parser object. See argparse module documentation for details.
+ stock_list The caller can use this parameter to request certain stock parameters
+ offered by this function. For example, this function will define a
+ "quiet" option upon request. This includes stop help text and parm
+ checking. The stock_list is a list of tuples each of which consists of
+ an arg_name and a default value. Example: stock_list = [("test_mode",
+ 0), ("quiet", 1), ("debug", 0)]
"""
# This is a list of stock parms that we support.
@@ -146,10 +140,9 @@
__builtin__.arg_obj = arg_obj
__builtin__.parser = parser
- # For each command line parameter, create a corresponding global variable
- # and assign it the appropriate value. For example, if the command line
- # contained "--last_name='Smith', we'll create a global variable named
- # "last_name" with the value "Smith".
+ # For each command line parameter, create a corresponding global variable and assign it the appropriate
+ # value. For example, if the command line contained "--last_name='Smith', we'll create a global variable
+ # named "last_name" with the value "Smith".
module = sys.modules['__main__']
for key in arg_obj.__dict__:
setattr(module, key, getattr(__builtin__.arg_obj, key))
@@ -160,14 +153,13 @@
def set_pgm_arg(var_value,
var_name=None):
r"""
- Set the value of the arg_obj.__dict__ entry named in var_name with the
- var_value provided. Also, set corresponding global variable.
+ Set the value of the arg_obj.__dict__ entry named in var_name with the var_value provided. Also, set
+ corresponding global variable.
Description of arguments:
var_value The value to set in the variable.
- var_name The name of the variable to set. This
- defaults to the name of the variable used
- for var_value when calling this function.
+ var_name The name of the variable to set. This defaults to the name of the
+ variable used for var_value when calling this function.
"""
if var_name is None:
@@ -187,14 +179,12 @@
def sprint_args(arg_obj,
indent=0):
r"""
- sprint_var all of the arguments found in arg_obj and return the result as
- a string.
+ sprint_var all of the arguments found in arg_obj and return the result as a string.
Description of arguments:
- arg_obj An argument object such as is returned by
- the argparse parse_args() method.
- indent The number of spaces to indent each line
- of output.
+ arg_obj An argument object such as is returned by the argparse parse_args()
+ method.
+ indent The number of spaces to indent each line of output.
"""
col1_width = gp.dft_col1_width + indent
@@ -212,8 +202,7 @@
def gen_exit_function(signal_number=0,
frame=None):
r"""
- Execute whenever the program ends normally or with the signals that we
- catch (i.e. TERM, INT).
+ Execute whenever the program ends normally or with the signals that we catch (i.e. TERM, INT).
"""
gp.dprint_executing()
@@ -230,39 +219,33 @@
def gen_signal_handler(signal_number,
frame):
r"""
- Handle signals. Without a function to catch a SIGTERM or SIGINT, the
- program would terminate immediately with return code 143 and without
- calling the exit_function.
+ Handle signals. Without a function to catch a SIGTERM or SIGINT, the program would terminate immediately
+ with return code 143 and without calling the exit_function.
"""
- # The convention is to set up exit_function with atexit.register() so
- # there is no need to explicitly call exit_function from here.
+ # The convention is to set up exit_function with atexit.register() so there is no need to explicitly
+ # call exit_function from here.
gp.dprint_executing()
- # Calling exit prevents control from returning to the code that was
- # running when the signal was received.
+ # Calling exit prevents control from returning to the code that was running when the signal was received.
exit(0)
def gen_post_validation(exit_function=None,
signal_handler=None):
r"""
- Do generic post-validation processing. By "post", we mean that this is to
- be called from a validation function after the caller has done any
- validation desired. If the calling program passes exit_function and
- signal_handler parms, this function will register them. In other words,
- it will make the signal_handler functions get called for SIGINT and
- SIGTERM and will make the exit_function function run prior to the
- termination of the program.
+ Do generic post-validation processing. By "post", we mean that this is to be called from a validation
+ function after the caller has done any validation desired. If the calling program passes exit_function
+ and signal_handler parms, this function will register them. In other words, it will make the
+ signal_handler functions get called for SIGINT and SIGTERM and will make the exit_function function run
+ prior to the termination of the program.
Description of arguments:
- exit_function A function object pointing to the caller's
- exit function. This defaults to this
- module's gen_exit_function.
- signal_handler A function object pointing to the caller's
- signal_handler function. This defaults to
- this module's gen_signal_handler.
+ exit_function A function object pointing to the caller's exit function. This defaults
+ to this module's gen_exit_function.
+ signal_handler A function object pointing to the caller's signal_handler function. This
+ defaults to this module's gen_signal_handler.
"""
# Get defaults.
diff --git a/lib/gen_call_robot.py b/lib/gen_call_robot.py
index 9f67593..bce7c79 100755
--- a/lib/gen_call_robot.py
+++ b/lib/gen_call_robot.py
@@ -1,8 +1,8 @@
#!/usr/bin/env python
r"""
-This module provides functions which are useful to plug-ins call-point
-programs that wish to make external robot program calls.
+This module provides functions which are useful to plug-ins call-point programs that wish to make external
+robot program calls.
"""
import sys
@@ -30,21 +30,19 @@
outputdir, output, log, report, loglevel
- This function would typically be called prior to calling
- create_robot_cmd_string.
+ This function would typically be called prior to calling create_robot_cmd_string.
Description of argument(s):
- extra_prefix An extra prefix to be appended to the
- default prefix for output file names.
+ extra_prefix An extra prefix to be appended to the default prefix for output file
+ names.
"""
gp.dprint_executing()
AUTOBOOT_OPENBMC_NICKNAME = gm.get_mod_global("AUTOBOOT_OPENBMC_NICKNAME")
# Set values for call to create_robot_cmd_string.
- # Environment variable TMP_ROBOT_DIR_PATH can be set by the user to
- # indicate that robot-generated output should initially be written to the
- # specified temporary directory and then moved to the normal output
+ # Environment variable TMP_ROBOT_DIR_PATH can be set by the user to indicate that robot-generated output
+ # should initially be written to the specified temporary directory and then moved to the normal output
# location after completion.
outputdir =\
os.environ.get("TMP_ROBOT_DIR_PATH",
@@ -57,9 +55,8 @@
time_string = time.strftime("%y%m%d.%H%M%S", loc_time)
file_prefix = AUTOBOOT_OPENBMC_NICKNAME + "." + extra_prefix +\
time_string + "."
- # Environment variable SAVE_STATUS_POLICY governs when robot-generated
- # output files (e.g. the log.html) will be moved from TMP_ROBOT_DIR_PATH
- # to FFDC_DIR_PATH. Valid values are "ALWAYS", "NEVER" and "FAIL".
+ # Environment variable SAVE_STATUS_POLICY governs when robot-generated output files (e.g. the log.html)
+ # will be moved from TMP_ROBOT_DIR_PATH to FFDC_DIR_PATH. Valid values are "ALWAYS", "NEVER" and "FAIL".
SAVE_STATUS_POLICY = os.environ.get("SAVE_STATUS_POLICY", "ALWAYS")
if SAVE_STATUS_POLICY == "NEVER":
output = "NONE"
@@ -81,24 +78,21 @@
def init_robot_test_base_dir_path():
r"""
- Initialize and validate the environment variable, ROBOT_TEST_BASE_DIR_PATH
- and set corresponding global variable ROBOT_TEST_RUNNING_FROM_SB.
+ Initialize and validate the environment variable, ROBOT_TEST_BASE_DIR_PATH and set corresponding global
+ variable ROBOT_TEST_RUNNING_FROM_SB.
- If ROBOT_TEST_BASE_DIR_PATH is already set, this function will merely
- validate it. This function will also set environment variable
- ROBOT_TEST_RUNNING_FROM_SB when ROBOT_TEST_BASE_DIR_PATH is not pre-set.
+ If ROBOT_TEST_BASE_DIR_PATH is already set, this function will merely validate it. This function will
+ also set environment variable ROBOT_TEST_RUNNING_FROM_SB when ROBOT_TEST_BASE_DIR_PATH is not pre-set.
"""
# ROBOT_TEST_BASE_DIR_PATH will be set as follows:
- # This function will determine whether we are running in a user sandbox
- # or from a standard apolloxxx environment.
+ # This function will determine whether we are running in a user sandbox or from a standard apolloxxx
+ # environment.
# - User sandbox:
- # If there is a <developer's home dir>/git/openbmc-test-automation/,
- # ROBOT_TEST_BASE_DIR_PATH will be set to that path. Otherwise, we set it
- # to <program dir path>/git/openbmc-test-automation/
+ # If there is a <developer's home dir>/git/openbmc-test-automation/, ROBOT_TEST_BASE_DIR_PATH will be
+ # set to that path. Otherwise, we set it to <program dir path>/git/openbmc-test-automation/
# - Not in user sandbox:
- # ROBOT_TEST_BASE_DIR_PATH will be set to <program dir
- # path>/git/openbmc-test-automation/
+ # ROBOT_TEST_BASE_DIR_PATH will be set to <program dir path>/git/openbmc-test-automation/
ROBOT_TEST_BASE_DIR_PATH = os.environ.get('ROBOT_TEST_BASE_DIR_PATH', "")
ROBOT_TEST_RUNNING_FROM_SB = \
@@ -111,8 +105,8 @@
else:
suffix = "git/openbmc-test-automation/"
- # Determine whether we're running out of a developer sandbox or
- # simply out of an apolloxxx/bin path.
+ # Determine whether we're running out of a developer sandbox or simply out of an apolloxxx/bin
+ # path.
shell_rc, out_buf = gc.shell_cmd('dirname $(which gen_print.py)',
quiet=(not debug), print_output=0)
executable_base_dir_path = os.path.realpath(out_buf.rstrip()) + "/"
@@ -159,20 +153,16 @@
def init_robot_file_path(robot_file_path):
r"""
- Determine full path name for the file path passed in robot_file_path and
- return it.
+ Determine full path name for the file path passed in robot_file_path and return it.
- If robot_file_path contains a fully qualified path name, this function
- will verify that the file exists. If robot_file_path contains a relative
- path, this function will search for the file and set robot_file_path so
- that it contains the absolute path to the robot file. This function will
- search for the robot file using the raw_robot_file_search_path (defined
- above). Note that if ROBOT_TEST_BASE_DIR_PATH is not set, this function
- will call init_robot_test_base_dir_path to set it.
+ If robot_file_path contains a fully qualified path name, this function will verify that the file exists.
+ If robot_file_path contains a relative path, this function will search for the file and set
+ robot_file_path so that it contains the absolute path to the robot file. This function will search for
+ the robot file using the raw_robot_file_search_path (defined above). Note that if
+ ROBOT_TEST_BASE_DIR_PATH is not set, this function will call init_robot_test_base_dir_path to set it.
Description of arguments:
- robot_file_path The absolute or relative path to a robot
- file.
+ robot_file_path The absolute or relative path to a robot file.
"""
gv.valid_value(robot_file_path)
@@ -217,9 +207,8 @@
def get_robot_parm_names():
r"""
- Return a list containing all of the long parm names (e.g. --outputdir)
- supported by the robot program. Double dashes are not included in the
- names returned.
+ Return a list containing all of the long parm names (e.g. --outputdir) supported by the robot program.
+ Double dashes are not included in the names returned.
"""
cmd_buf = "robot -h | egrep " +\
@@ -232,32 +221,26 @@
def create_robot_cmd_string(robot_file_path, *parms):
r"""
- Create a robot command string and return it. On failure, return an empty
- string.
+ Create a robot command string and return it. On failure, return an empty string.
Description of arguments:
robot_file_path The path to the robot file to be run.
- parms The list of parms to be included in the
- command string. The name of each variable
- in this list must be the same as the name
- of the corresponding parm. This function
- figures out that name. This function is
- also able to distinguish robot parms (e.g.
- --outputdir) from robot program parms (all
- other parms which will be passed as "-v
- PARM_NAME:parm_value")..
+ parms The list of parms to be included in the command string. The name of each
+ variable in this list must be the same as the name of the corresponding
+ parm. This function figures out that name. This function is also able
+ to distinguish robot parms (e.g. --outputdir) from robot program parms
+ (all other parms which will be passed as "-v PARM_NAME:parm_value")..
Example:
The following call to this function...
- cmd_buf = create_robot_cmd_string("tools/start_sol_console.robot",
- OPENBMC_HOST, quiet, test_mode, debug, outputdir, output, log, report)
+ cmd_buf = create_robot_cmd_string("tools/start_sol_console.robot", OPENBMC_HOST, quiet, test_mode, debug,
+ outputdir, output, log, report)
Would return a string something like this.
robot -v OPENBMC_HOST:beye6 -v quiet:0 -v test_mode:1 -v debug:1
- --outputdir=/gsa/ausgsa/projects/a/status
- --output=beye6.OS_Console.output.xml --log=beye6.OS_Console.log.html
- --report=beye6.OS_Console.report.html tools/start_sol_console.robot
+ --outputdir=/gsa/ausgsa/projects/a/status --output=beye6.OS_Console.output.xml
+ --log=beye6.OS_Console.log.html --report=beye6.OS_Console.report.html tools/start_sol_console.robot
"""
robot_file_path = init_robot_file_path(robot_file_path)
@@ -296,17 +279,14 @@
gzip=None):
r"""
Process robot output files which can involve several operations:
- - If the files are in a temporary location, using SAVE_STATUS_POLICY to
- decide whether to move them to a permanent location or to delete them.
+ - If the files are in a temporary location, using SAVE_STATUS_POLICY to decide whether to move them to a
+ permanent location or to delete them.
- Gzipping them.
Description of argument(s):
- robot_cmd_buf The complete command string used to invoke
- robot.
- robot_rc The return code from running the robot
- command string.
- gzip Indicates whether robot-generated output
- should be gzipped.
+ robot_cmd_buf The complete command string used to invoke robot.
+ robot_rc The return code from running the robot command string.
+ gzip Indicates whether robot-generated output should be gzipped.
"""
robot_cmd_buf = gm.dft(robot_cmd_buf, gcr_last_robot_cmd_buf)
@@ -314,15 +294,14 @@
gzip = gm.dft(gzip, int(os.environ.get("GZIP_ROBOT", "1")))
if robot_cmd_buf == "":
- # This can legitimately occur if this function is called from an
- # exit_function without the program having ever run robot_cmd_fnc.
+ # This can legitimately occur if this function is called from an exit_function without the program
+ # having ever run robot_cmd_fnc.
return
SAVE_STATUS_POLICY = os.environ.get("SAVE_STATUS_POLICY", "ALWAYS")
gp.qprint_vars(SAVE_STATUS_POLICY)
- # When SAVE_STATUS_POLICY is "NEVER" robot output files don't even get
- # generated.
+ # When SAVE_STATUS_POLICY is "NEVER" robot output files don't even get generated.
if SAVE_STATUS_POLICY == "NEVER":
return
@@ -355,15 +334,13 @@
# Update the values in file_list.
file_list = re.sub(" ", ".gz ", file_list) + ".gz"
- # It TMP_ROBOT_DIR_PATH is set, it means the caller wanted the robot
- # output initially directed to TMP_ROBOT_DIR_PATH but later moved to
- # FFDC_DIR_PATH. Otherwise, we're done.
+ # It TMP_ROBOT_DIR_PATH is set, it means the caller wanted the robot output initially directed to
+ # TMP_ROBOT_DIR_PATH but later moved to FFDC_DIR_PATH. Otherwise, we're done.
if os.environ.get("TMP_ROBOT_DIR_PATH", "") is "":
return
- # We're directing these to the FFDC dir path so that they'll be subjected
- # to FFDC cleanup.
+ # We're directing these to the FFDC dir path so that they'll be subjected to FFDC cleanup.
target_dir_path = os.environ.get("FFDC_DIR_PATH",
os.environ.get("HOME", ".")
+ "/ffdc")
@@ -384,14 +361,13 @@
r"""
Run the robot command string.
- This function will set the various PATH variables correctly so that you
- are running the proper version of all imported files, etc.
+ This function will set the various PATH variables correctly so that you are running the proper version of
+ all imported files, etc.
Description of argument(s):
robot_cmd_buf The complete robot command string.
- robot_jail Indicates that this is to run in "robot
- jail" meaning without visibility to any
- apolloxxx import files, programs, etc.
+ robot_jail Indicates that this is to run in "robot jail" meaning without visibility
+ to any apolloxxx import files, programs, etc.
"""
gv.valid_value(robot_cmd_buf)
@@ -433,13 +409,11 @@
os.environ["SAVED_PATH"] = os.environ.get("PATH", "")
if robot_jail:
- # Make sure required programs like python and robot can be found in
- # the new restricted PATH.
+ # Make sure required programs like python and robot can be found in the new restricted PATH.
required_programs = "python robot"
- # It is expected that there will be a "python" program in the tool
- # base bin path which is really a link to select_version. Ditto for
- # "robot". Call each with the --print_only option to get the paths to
- # the "real" programs.
+ # It is expected that there will be a "python" program in the tool base bin path which is really a
+ # link to select_version. Ditto for "robot". Call each with the --print_only option to get the
+ # paths to the "real" programs.
cmd_buf = "for program in " + required_programs \
+ " ; do dirname $(${program} --print_only) ; done 2>/dev/null"
rc, out_buf = gc.shell_cmd(cmd_buf, quiet=1, print_output=0)
diff --git a/lib/gen_misc.py b/lib/gen_misc.py
index 92c208c..19c3d6e 100755
--- a/lib/gen_misc.py
+++ b/lib/gen_misc.py
@@ -57,8 +57,7 @@
The PATH environment variable dictates the results of this function.
Description of arguments:
- file_path The relative file path (e.g. "my_file" or
- "lib/my_file").
+ file_path The relative file path (e.g. "my_file" or "lib/my_file").
"""
shell_rc, out_buf = gc.cmd_fnc_u("which " + file_path, quiet=1,
@@ -83,8 +82,7 @@
path,
position=0):
r"""
- Add new_path to path, provided that path doesn't already contain new_path,
- and return the result.
+ Add new_path to path, provided that path doesn't already contain new_path, and return the result.
Example:
If PATH has a value of "/bin/user:/lib/user". The following code:
@@ -94,15 +92,11 @@
will change PATH to "/tmp/new_path:/bin/user:/lib/user".
Description of argument(s):
- new_path The path to be added. This function will
- strip the trailing slash.
- path The path value to which the new_path
- should be added.
- position The position in path where the new_path
- should be added. 0 means it should be
- added to the beginning, 1 means add it as
- the 2nd item, etc. sys.maxsize means it
- should be added to the end.
+ new_path The path to be added. This function will strip the trailing slash.
+ path The path value to which the new_path should be added.
+ position The position in path where the new_path should be added. 0 means it
+ should be added to the beginning, 1 means add it as the 2nd item, etc.
+ sys.maxsize means it should be added to the end.
"""
path_list = list(filter(None, path.split(":")))
@@ -126,8 +120,7 @@
Description of arguments:
value The value to be returned.
- default The default value to return if value is
- None.
+ default The default value to return if value is None.
"""
return default if value is None else value
@@ -143,12 +136,9 @@
calling get_variable_value.
Description of arguments:
- var_name The name of the variable whose value is
- sought.
- default The value to return if the global does not
- exist.
- mod_name The name of the module containing the
- global variable.
+ var_name The name of the variable whose value is sought.
+ default The value to return if the global does not exist.
+ mod_name The name of the module containing the global variable.
"""
if robot_env:
@@ -183,9 +173,8 @@
Description of arguments:
var_value The value being evaluated.
- default The value to be returned if var_value is
- None AND the global variable of the same
- name does not exist.
+ default The value to be returned if var_value is None AND the global variable of
+ the same name does not exist.
"""
var_name = gp.get_arg_name(0, 1, stack_frame_ix=2)
@@ -201,11 +190,9 @@
Description of arguments:
var_value The value to set in the variable.
- mod_name The name of the module whose variable is
- to be set.
- var_name The name of the variable to set. This
- defaults to the name of the variable used
- for var_value when calling this function.
+ mod_name The name of the module whose variable is to be set.
+ var_name The name of the variable to set. This defaults to the name of the
+ variable used for var_value when calling this function.
"""
try:
@@ -224,26 +211,23 @@
def my_parm_file(prop_file_path):
r"""
- Read a properties file, put the keys/values into a dictionary and return
- the dictionary.
+ Read a properties file, put the keys/values into a dictionary and return the dictionary.
The properties file must have the following format:
var_name<= or :>var_value
- Comment lines (those beginning with a "#") and blank lines are allowed and
- will be ignored. Leading and trailing single or double quotes will be
- stripped from the value. E.g.
+ Comment lines (those beginning with a "#") and blank lines are allowed and will be ignored. Leading and
+ trailing single or double quotes will be stripped from the value. E.g.
var1="This one"
Quotes are stripped so the resulting value for var1 is:
This one
Description of arguments:
- prop_file_path The caller should pass the path to the
- properties file.
+ prop_file_path The caller should pass the path to the properties file.
"""
- # ConfigParser expects at least one section header in the file (or you
- # get ConfigParser.MissingSectionHeaderError). Properties files don't
- # need those so I'll write a dummy section header.
+ # ConfigParser expects at least one section header in the file (or you get
+ # ConfigParser.MissingSectionHeaderError). Properties files don't need those so I'll write a dummy
+ # section header.
try:
string_file = StringIO.StringIO()
@@ -282,16 +266,11 @@
list is one line from the file.
Description of arguments:
- file_path The path to the file (relative or
- absolute).
- newlines Include newlines from the file in the
- results.
- comments Include comment lines and blank lines in
- the results. Comment lines are any that
- begin with 0 or more spaces followed by
- the pound sign ("#").
- trim Trim white space from the beginning and
- end of each line.
+ file_path The path to the file (relative or absolute).
+ newlines Include newlines from the file in the results.
+ comments Include comment lines and blank lines in the results. Comment lines are
+ any that begin with 0 or more spaces followed by the pound sign ("#").
+ trim Trim white space from the beginning and end of each line.
"""
lines = []
@@ -323,9 +302,8 @@
def return_path_list():
r"""
- This function will split the PATH environment variable into a PATH_LIST
- and return it. Each element in the list will be normalized and have a
- trailing slash added.
+ This function will split the PATH environment variable into a PATH_LIST and return it. Each element in
+ the list will be normalized and have a trailing slash added.
"""
PATH_LIST = os.environ['PATH'].split(":")
@@ -365,9 +343,8 @@
parm The string to be quoted.
"""
- # If any of these characters are found in the parm string, then the
- # string should be quoted. This list is by no means complete and should
- # be expanded as needed by the developer of this function.
+ # If any of these characters are found in the parm string, then the string should be quoted. This list
+ # is by no means complete and should be expanded as needed by the developer of this function.
# Spaces
# Single or double quotes.
# Bash variables (therefore, any string with a "$" may need quoting).
@@ -391,14 +368,12 @@
def get_host_name_ip(host=None,
short_name=0):
r"""
- Get the host name and the IP address for the given host and return them as
- a tuple.
+ Get the host name and the IP address for the given host and return them as a tuple.
Description of argument(s):
host The host name or IP address to be obtained.
- short_name Include the short host name in the
- returned tuple, i.e. return host, ip and
- short_host.
+ short_name Include the short host name in the returned tuple, i.e. return host, ip
+ and short_host.
"""
host = dft(host, socket.gethostname())
@@ -465,8 +440,7 @@
var1: -15
var1: 0xfffffffffffffff1
- The same code but with var1 set to 0x000000000000007f produces the
- following:
+ The same code but with var1 set to 0x000000000000007f produces the following:
var1: 127
var1: 0x000000000000007f
var1: 127
@@ -474,9 +448,8 @@
Description of argument(s):
number The number to be converted.
- bit_width The number of bits that defines a complete
- hex value. Typically, this would be a
- multiple of 32.
+ bit_width The number of bits that defines a complete hex value. Typically, this
+ would be a multiple of 32.
"""
if bit_width is None:
@@ -497,8 +470,8 @@
def get_child_pids(quiet=1):
r"""
- Get and return a list of pids representing all first-generation processes
- that are the children of the current process.
+ Get and return a list of pids representing all first-generation processes that are the children of the
+ current process.
Example:
@@ -510,8 +483,7 @@
children[0]: 9123
Description of argument(s):
- quiet Display output to stdout detailing how
- this child pids are obtained.
+ quiet Display output to stdout detailing how this child pids are obtained.
"""
if psutil_imported:
@@ -524,34 +496,30 @@
ps_cmd_buf = "ps --no-headers --ppid " + str(os.getpid()) +\
" -o pid,args"
- # Route the output of ps to a temporary file for later grepping.
- # Avoid using " | grep" in the ps command string because it creates
- # yet another process which is of no interest to the caller.
+ # Route the output of ps to a temporary file for later grepping. Avoid using " | grep" in the ps
+ # command string because it creates yet another process which is of no interest to the caller.
temp = tempfile.NamedTemporaryFile()
temp_file_path = temp.name
gc.shell_cmd(ps_cmd_buf + " > " + temp_file_path,
print_output=print_output)
# Sample contents of the temporary file:
# 30703 sleep 2
- # 30795 /bin/bash -c ps --no-headers --ppid 30672 -o pid,args >
- # /tmp/tmpqqorWY
- # Use egrep to exclude the "ps" process itself from the results
- # collected with the prior shell_cmd invocation. Only the other
- # children are of interest to the caller. Use cut on the grep results
- # to obtain only the pid column.
+ # 30795 /bin/bash -c ps --no-headers --ppid 30672 -o pid,args > /tmp/tmpqqorWY
+ # Use egrep to exclude the "ps" process itself from the results collected with the prior shell_cmd
+ # invocation. Only the other children are of interest to the caller. Use cut on the grep results to
+ # obtain only the pid column.
rc, output = \
gc.shell_cmd("egrep -v '" + re.escape(ps_cmd_buf) + "' "
+ temp_file_path + " | cut -c1-5",
print_output=print_output)
- # Split the output buffer by line into a list. Strip each element of
- # extra spaces and convert each element to an integer.
+ # Split the output buffer by line into a list. Strip each element of extra spaces and convert each
+ # element to an integer.
return map(int, map(str.strip, filter(None, output.split("\n"))))
def json_loads_multiple(buffer):
r"""
- Convert the contents of the buffer to a JSON array, run json.loads() on it
- and return the result.
+ Convert the contents of the buffer to a JSON array, run json.loads() on it and return the result.
The buffer is expected to contain one or more JSON objects.
@@ -559,12 +527,10 @@
buffer A string containing several JSON objects.
"""
- # Any line consisting of just "}", which indicates the end of an object,
- # should have a comma appended.
+ # Any line consisting of just "}", which indicates the end of an object, should have a comma appended.
regex = "([\\r\\n])[\\}]([\\r\\n])"
buffer = re.sub(regex, "\\1},\\2", buffer, 1)
- # Remove the comma from after the final object and place the whole buffer
- # inside square brackets.
+ # Remove the comma from after the final object and place the whole buffer inside square brackets.
buffer = "[" + re.sub(",([\r\n])$", "\\1}", buffer, 1) + "]"
if gp.robot_env:
return json.loads(buffer, object_pairs_hook=DotDict)
@@ -576,8 +542,7 @@
r"""
Return a date/time stamp in the following format: yymmdd.HHMMSS
- This value is suitable for including in file names. Example
- file1.181001.171716.status
+ This value is suitable for including in file names. Example file1.181001.171716.status
"""
return time.strftime("%y%m%d.%H%M%S", time.localtime(time.time()))
@@ -587,8 +552,7 @@
r"""
Return a list of all the function names currently in the call stack.
- This function's name will be at offset 0. This function's caller's name
- will be at offset 1 and so on.
+ This function's name will be at offset 0. This function's caller's name will be at offset 1 and so on.
"""
return [str(stack_frame[3]) for stack_frame in inspect.stack()]
@@ -619,15 +583,13 @@
Convert the version string to a tuple and return it.
Description of argument(s):
- version A version string whose format is "n[.n]"
- (e.g. "3.6.3", "3", etc.).
+ version A version string whose format is "n[.n]" (e.g. "3.6.3", "3", etc.).
"""
return tuple(map(int, (version.split("."))))
-# Note: Stripping out any revision code data (e.g. "3.6.3rc1" will become
-# "3.6.3").
+# Note: Stripping out any revision code data (e.g. "3.6.3rc1" will become "3.6.3").
python_version = \
version_tuple(re.sub("rc[^ ]+", "", sys.version).split(" ")[0])
ordered_dict_version = version_tuple("3.6")
diff --git a/lib/gen_plug_in.py b/lib/gen_plug_in.py
index 66a8583..95776d5 100755
--- a/lib/gen_plug_in.py
+++ b/lib/gen_plug_in.py
@@ -33,9 +33,8 @@
r"""
Get plug-in base paths and return them as a list.
- This function searches the PATH_LIST (created from PATH environment
- variable) for any paths that have a "plug_ins" subdirectory. All such
- paths are considered plug_in_base paths.
+ This function searches the PATH_LIST (created from PATH environment variable) for any paths that have a
+ "plug_ins" subdirectory. All such paths are considered plug_in_base paths.
"""
global PATH_LIST
@@ -50,19 +49,17 @@
return plug_in_base_path_list
-# Define global plug_in_base_path_list and call get_plug_in_base_paths to set
-# its value.
+# Define global plug_in_base_path_list and call get_plug_in_base_paths to set its value.
plug_in_base_path_list = get_plug_in_base_paths()
def find_plug_in_package(plug_in_name):
r"""
- Find and return the normalized directory path of the specified plug in.
- This is done by searching the global plug_in_base_path_list.
+ Find and return the normalized directory path of the specified plug in. This is done by searching the
+ global plug_in_base_path_list.
Description of arguments:
- plug_in_name The unqualified name of the plug-in
- package.
+ plug_in_name The unqualified name of the plug-in package.
"""
global plug_in_base_path_list
@@ -79,15 +76,12 @@
def validate_plug_in_package(plug_in_dir_path,
mch_class="obmc"):
r"""
- Validate the plug in package and return the normalized plug-in directory
- path.
+ Validate the plug in package and return the normalized plug-in directory path.
Description of arguments:
- plug_in_dir_path The "relative" or absolute path to a plug
- in package directory.
- mch_class The class of machine that we are testing
- (e.g. "op" = "open power", "obmc" = "open
- bmc", etc).
+ plug_in_dir_path The "relative" or absolute path to a plug in package directory.
+ mch_class The class of machine that we are testing (e.g. "op" = "open power",
+ "obmc" = "open bmc", etc).
"""
gp.dprint_executing()
@@ -101,8 +95,7 @@
+ plug_in_dir_path + "\" does not exist.\n")
exit(1)
else:
- # The plug_in_dir_path is actually a simple name (e.g.
- # "OBMC_Sample")...
+ # The plug_in_dir_path is actually a simple name (e.g. "OBMC_Sample")...
candidate_plug_in_dir_path = find_plug_in_package(plug_in_dir_path)
if candidate_plug_in_dir_path == "":
global PATH_LIST
@@ -129,16 +122,14 @@
def return_integrated_plug_ins(mch_class="obmc"):
r"""
- Return a list of integrated plug-ins. Integrated plug-ins are plug-ins
- which are selected without regard for whether the user has specified them.
- In other words, they are "integrated" into the program suite. The
- programmer designates a plug-in as integrated by putting a file named
- "integrated" into the plug-in package directory.
+ Return a list of integrated plug-ins. Integrated plug-ins are plug-ins which are selected without regard
+ for whether the user has specified them. In other words, they are "integrated" into the program suite.
+ The programmer designates a plug-in as integrated by putting a file named "integrated" into the plug-in
+ package directory.
Description of arguments:
- mch_class The class of machine that we are testing
- (e.g. "op" = "open power", "obmc" = "open
- bmc", etc).
+ mch_class The class of machine that we are testing (e.g. "op" = "open power",
+ "obmc" = "open bmc", etc).
"""
global plug_in_base_path_list
@@ -171,16 +162,13 @@
def return_plug_in_packages_list(plug_in_dir_paths,
mch_class="obmc"):
r"""
- Return a list of plug-in packages given the plug_in_dir_paths string.
- This function calls validate_plug_in_package so it will fail if
- plug_in_dir_paths contains any invalid plug-ins.
+ Return a list of plug-in packages given the plug_in_dir_paths string. This function calls
+ validate_plug_in_package so it will fail if plug_in_dir_paths contains any invalid plug-ins.
Description of arguments:
- plug_in_dir_path The "relative" or absolute path to a plug
- in package directory.
- mch_class The class of machine that we are testing
- (e.g. "op" = "open power", "obmc" = "open
- bmc", etc).
+ plug_in_dir_path The "relative" or absolute path to a plug in package directory.
+ mch_class The class of machine that we are testing (e.g. "op" = "open power",
+ "obmc" = "open bmc", etc).
"""
if plug_in_dir_paths != "":
@@ -190,9 +178,9 @@
# Get a list of integrated plug-ins (w/o full path names).
integrated_plug_ins_list = return_integrated_plug_ins(mch_class)
- # Put both lists together in plug_in_packages_list with no duplicates.
- # NOTE: This won't catch duplicates if the caller specifies the full path
- # name of a native plug-in but that should be rare enough.
+ # Put both lists together in plug_in_packages_list with no duplicates. NOTE: This won't catch
+ # duplicates if the caller specifies the full path name of a native plug-in but that should be rare
+ # enough.
plug_in_packages_list = plug_in_packages_list + integrated_plug_ins_list
diff --git a/lib/gen_robot_keyword.py b/lib/gen_robot_keyword.py
index 91a5f0c..1bac73d 100755
--- a/lib/gen_robot_keyword.py
+++ b/lib/gen_robot_keyword.py
@@ -15,30 +15,25 @@
r"""
Run the given keyword, return the status and the keyword return values.
- The advantage of using this function verses having robot simply run your
- keyword is the handling of parameters like quiet, test_mode and ignore.
+ The advantage of using this function verses having robot simply run your keyword is the handling of
+ parameters like quiet, test_mode and ignore.
Description of arguments:
keyword_buf The keyword string to be run.
- quiet Indicates whether this function should run
- the pissuing function to print 'Issuing:
- <keyword string>' to stdout.
- test_mode If test_mode is set, this function will
- not actually run the command. If quiet is
- 0, it will print a message indicating what
- it would have run (e.g. "Issuing:
- (test_mode) your command").
- ignore Ignore errors from running keyword. If
- this is 0, this function will fail with
- whatever error occurred when running the
- keyword.
+ quiet Indicates whether this function should run the pissuing function to print
+ 'Issuing: <keyword string>' to stdout.
+ test_mode If test_mode is set, this function will not actually run the command. If
+ quiet is 0, it will print a message indicating what it would have run
+ (e.g. "Issuing: (test_mode) your command").
+ ignore Ignore errors from running keyword. If this is 0, this function will
+ fail with whatever error occurred when running the keyword.
Example usage from a robot script:
${status} ${ret_values}= Run Key My Keyword \ Arg1 \ Arg2
- Note that to get robot to pass your command + args as a single string to
- this function, you must escape extra spaces with a backslash.
+ Note that to get robot to pass your command + args as a single string to this function, you must escape
+ extra spaces with a backslash.
Also note that ret_values is a python list:
ret_values:
@@ -51,11 +46,9 @@
test_mode = int(gp.get_var_value(test_mode, 0))
ignore = int(ignore)
- # Convert the keyword_buf into a list split wherever 2 or more spaces are
- # found.
+ # Convert the keyword_buf into a list split wherever 2 or more spaces are found.
keyword_list = keyword_buf.split(' ')
- # Strip spaces from each argument to make the output look clean and
- # uniform.
+ # Strip spaces from each argument to make the output look clean and uniform.
keyword_list = [item.strip(' ') for item in keyword_list]
if not quiet:
@@ -87,12 +80,10 @@
quiet=None,
ignore=0):
r"""
- Run keyword unconditionally (i.e. without regard to global test_mode
- setting).
+ Run keyword unconditionally (i.e. without regard to global test_mode setting).
- This function will simply call the run_key function passing on all of the
- callers parameters except test_mode which will be hard-coded to 0. See
- run_key (above) for details.
+ This function will simply call the run_key function passing on all of the callers parameters except
+ test_mode which will be hard-coded to 0. See run_key (above) for details.
See the proglog of "run_key" function above for description of arguments.
"""
diff --git a/lib/gen_robot_plug_in.py b/lib/gen_robot_plug_in.py
index 1088cb5..035f1f7 100755
--- a/lib/gen_robot_plug_in.py
+++ b/lib/gen_robot_plug_in.py
@@ -1,8 +1,7 @@
#!/usr/bin/env python
r"""
-This module provides functions which are useful for running plug-ins from a
-robot program.
+This module provides functions which are useful for running plug-ins from a robot program.
"""
import sys
@@ -19,15 +18,13 @@
def rvalidate_plug_ins(plug_in_dir_paths,
quiet=1):
r"""
- Call the external validate_plug_ins.py program which validates the plug-in
- dir paths given to it. Return a list containing a normalized path for
- each plug-in selected.
+ Call the external validate_plug_ins.py program which validates the plug-in dir paths given to it. Return
+ a list containing a normalized path for each plug-in selected.
Description of arguments:
- plug_in_dir_paths A colon-separated list of plug-in
- directory paths.
- quiet If quiet is set to 1, this function will
- NOT write status messages to stdout.
+ plug_in_dir_paths A colon-separated list of plug-in directory paths.
+ quiet If quiet is set to 1, this function will NOT write status messages to
+ stdout.
"""
cmd_buf = "validate_plug_ins.py \"" + plug_in_dir_paths + "\""
@@ -54,76 +51,48 @@
debug=None,
return_history=False):
r"""
- Call the external process_plug_in_packages.py to process the plug-in
- packages. Return the following:
+ Call the external process_plug_in_packages.py to process the plug-in packages. Return the following:
rc The return code - 0 = PASS, 1 = FAIL.
- shell_rc The shell return code returned by
- process_plug_in_packages.py.
+ shell_rc The shell return code returned by process_plug_in_packages.py.
failed_plug_in_name The failed plug in name (if any).
Description of arguments:
plug_in_packages_list A python list of plug-in directory paths.
- call_point The call point program to be called for
- each plug-in package (e.g. post_boot).
- This name should not include the "cp_"
- prefix.
- shell_rc The user may supply a value other than
- zero to indicate an acceptable non-zero
- return code. For example, if this value
- equals 0x00000200, it means that for each
- plug-in call point that runs, a 0x00000200
- will not be counted as a failure.
- stop_on_plug_in_failure If this parameter is set to 1, this
- program will stop and return non-zero if
- the call point program from any plug-in
- directory fails. Conversely, if it is set
- to false, this program will run the call
- point program from each and every plug-in
- directory regardless of their return
- values. Typical example cases where you'd
- want to run all plug-in call points
- regardless of success or failure would be
- "cleanup" or "ffdc" call points.
- stop_on_non_zero_rc If this parm is set to 1 and a plug-in
- call point program returns a valid
- non-zero return code (see "shell_rc" parm
- above), this program will stop processing
- and return 0 (success). Since this
- constitutes a successful exit, this would
- normally be used where the caller wishes
- to stop processing if one of the plug-in
- directory call point programs returns a
- special value indicating that some special
- case has been found. An example might be
- in calling some kind of "check_errl" call
- point program. Such a call point program
- might return a 2 (i.e. 0x00000200) to
- indicate that a given error log entry was
- found in an "ignore" list and is therefore
- to be ignored. That being the case, no
- other "check_errl" call point program
- would need to be called.
- release_type The type of release being tested (e.g.
- "obmc", "op", "fips"). This influences
- which integrated plug-ins are selected.
- quiet If quiet is set to 1, this function will
- NOT write status messages to stdout. This
- will default to the global quiet program
- parm or to 0.
- debug If this parameter is set to 1, this
- function will print additional debug
- information. This is mainly to be used by
- the developer of this function. This will
- default to the global quiet program parm
- or to 0.
- return_history In addition to rc, shell_rc and
- failed_plug_in_name, return a list
- containing historical output that looks
- like the following:
+ call_point The call point program to be called for each plug-in package (e.g.
+ post_boot). This name should not include the "cp_" prefix.
+ shell_rc The user may supply a value other than zero to indicate an acceptable
+ non-zero return code. For example, if this value equals 0x00000200, it
+ means that for each plug-in call point that runs, a 0x00000200 will not
+ be counted as a failure.
+ stop_on_plug_in_failure If this parameter is set to 1, this program will stop and return non-zero
+ if the call point program from any plug-in directory fails. Conversely,
+ if it is set to false, this program will run the call point program from
+ each and every plug-in directory regardless of their return values.
+ Typical example cases where you'd want to run all plug-in call points
+ regardless of success or failure would be "cleanup" or "ffdc" call points.
+ stop_on_non_zero_rc If this parm is set to 1 and a plug-in call point program returns a valid
+ non-zero return code (see "shell_rc" parm above), this program will stop
+ processing and return 0 (success). Since this constitutes a successful
+ exit, this would normally be used where the caller wishes to stop
+ processing if one of the plug-in directory call point programs returns a
+ special value indicating that some special case has been found. An
+ example might be in calling some kind of "check_errl" call point program.
+ Such a call point program might return a 2 (i.e. 0x00000200) to indicate
+ that a given error log entry was found in an "ignore" list and is
+ therefore to be ignored. That being the case, no other "check_errl" call
+ point program would need to be called.
+ release_type The type of release being tested (e.g. "obmc", "op", "fips"). This
+ influences which integrated plug-ins are selected.
+ quiet If quiet is set to 1, this function will NOT write status messages to
+ stdout. This will default to the global quiet program parm or to 0.
+ debug If this parameter is set to 1, this function will print additional debug
+ information. This is mainly to be used by the developer of this
+ function. This will default to the global quiet program parm or to 0.
+ return_history In addition to rc, shell_rc and failed_plug_in_name, return a list
+ containing historical output that looks like the following:
history:
- history[0]: #(CDT) 2018/10/30 12:25:49 - Running
- OBMC_Sample/cp_post_stack
+ history[0]: #(CDT) 2018/10/30 12:25:49 - Running OBMC_Sample/cp_post_stack
"""
rc = 0
@@ -185,15 +154,13 @@
else:
history = []
- # As process_plug_in_packages.py help text states, it will print the
- # values of failed_plug_in_name and shell_rc in the following format:
+ # As process_plug_in_packages.py help text states, it will print the values of failed_plug_in_name and
+ # shell_rc in the following format:
# failed_plug_in_name: <failed plug-in value, if any>
- # shell_rc: <shell return code value of last
- # call point program>
+ # shell_rc: <shell return code value of last call point program>
- # We want to obtain those values from the output. To make the task
- # simpler, we'll start by grepping the output for lines that might fit
- # such a format:
+ # We want to obtain those values from the output. To make the task simpler, we'll start by grepping the
+ # output for lines that might fit such a format:
# A valid bash variable against the left margin followed by...
# - A colon followed by...
# - Zero or more spaces
diff --git a/lib/gen_robot_print.py b/lib/gen_robot_print.py
index c03c9a3..7dd1384 100755
--- a/lib/gen_robot_print.py
+++ b/lib/gen_robot_print.py
@@ -19,26 +19,21 @@
r"""
Sprint the values of one or more variables to the console.
- This is a robot re-definition of the sprint_vars function in gen_print.py.
- Given a list of variable names, this keyword will string print each
- variable name and value such that each value lines up in the same column
- as messages printed with sprint_time().
+ This is a robot re-definition of the sprint_vars function in gen_print.py. Given a list of variable
+ names, this keyword will string print each variable name and value such that each value lines up in the
+ same column as messages printed with sprint_time().
Description of argument(s):
- args The names of the variables to be printed
- (e.g. var1 rather than ${var1}).
- kwargs See sprint_varx in gen_print.py for
- descriptions of all other arguments.
+ args The names of the variables to be printed (e.g. var1 rather than ${var1}).
+ kwargs See sprint_varx in gen_print.py for descriptions of all other arguments.
"""
if 'fmt' in kwargs:
- # Find format option names in kwargs['fmt'] and wrap them with "gp."
- # and "()" to make them into function calls. For example, verbose
- # would be converted to "gp.verbose()". This allows the user to
- # simply specify "fmt=verbose" (vs. fmt=gp.verbose()).
- # Note "terse" has been explicitly added for backward compatibility.
- # Once the repo has been purged of its use, this code can return to
- # its original form.
+ # Find format option names in kwargs['fmt'] and wrap them with "gp." and "()" to make them into
+ # function calls. For example, verbose would be converted to "gp.verbose()". This allows the user
+ # to simply specify "fmt=verbose" (vs. fmt=gp.verbose()).
+ # Note "terse" has been explicitly added for backward compatibility. Once the repo has been purged
+ # of its use, this code can return to its original form.
regex = "(" + "|".join(gp.valid_fmts()) + "|terse)"
kwargs['fmt'] = \
re.sub(regex, "gp.\\1()", kwargs['fmt'])
@@ -53,14 +48,12 @@
def sprint_auto_vars(headers=0):
r"""
- String print all of the Automatic Variables described in the Robot User's
- Guide using sprint_vars.
+ String print all of the Automatic Variables described in the Robot User's Guide using sprint_vars.
NOTE: Not all automatic variables are guaranteed to exist.
Description of argument(s):
- headers This indicates that a header and footer
- should be printed.
+ headers This indicates that a header and footer should be printed.
"""
buffer = ""
@@ -99,28 +92,23 @@
gp.gp_print(buffer)
-# In the following section of code, we will dynamically create print versions
-# for several of the sprint functions defined above. For example, where we
-# have an sprint_vars() function defined above that returns formatted variable
-# print outs in a string, we will create a corresponding rprint_vars()
-# function that will print that string directly to stdout.
+# In the following section of code, we will dynamically create print versions for several of the sprint
+# functions defined above. For example, where we have an sprint_vars() function defined above that returns
+# formatted variable print outs in a string, we will create a corresponding rprint_vars() function that will
+# print that string directly to stdout.
-# It can be complicated to follow what's being created below. Here is an
-# example of the rprint_vars() function that will be created:
+# It can be complicated to follow what's being created below. Here is an example of the rprint_vars()
+# function that will be created:
# def rprint_vars(*args, **kwargs):
-# gp.gp_print(gp.replace_passwords(sprint_vars(*args, **kwargs)),
-# stream='stdout')
+# gp.gp_print(gp.replace_passwords(sprint_vars(*args, **kwargs)), stream='stdout')
# For sprint_vars (defined above), the following functions will be created:
# rprint_vars Robot Print Vars
-# rqprint_vars Robot Print Vars if ${quiet} is set to
-# ${0}.
-# rdprint_vars Robot Print Vars if ${debug} is set to
-# ${1}.
-# rlprint_vars Robot Print Vars to the log instead of to
-# the console.
+# rqprint_vars Robot Print Vars if ${quiet} is set to ${0}.
+# rdprint_vars Robot Print Vars if ${debug} is set to ${1}.
+# rlprint_vars Robot Print Vars to the log instead of to the console.
# Abbreviated names are created for all of the preceding function names:
# rpvars
@@ -128,22 +116,20 @@
# rdpvars
# rlpvars
-# Users are encouraged to only use the abbreviated forms for development but
-# to then ultimately switch to full names.
+# Users are encouraged to only use the abbreviated forms for development but to then ultimately switch to
+# full names.
# Rprint Vars (instead of Rpvars)
replace_dict = {'output_stream': 'stdout', 'mod_qualifier': 'gp.'}
gp_debug_print("gp.robot_env: " + str(gp.robot_env) + "\n")
-# func_names contains a list of all rprint functions which should be created
-# from their sprint counterparts.
+# func_names contains a list of all rprint functions which should be created from their sprint counterparts.
func_names = [
'print_vars', 'print_auto_vars'
]
-# stderr_func_names is a list of functions whose output should go to stderr
-# rather than stdout.
+# stderr_func_names is a list of functions whose output should go to stderr rather than stdout.
stderr_func_names = []
func_defs = gp.create_print_wrapper_funcs(func_names, stderr_func_names,
@@ -151,8 +137,7 @@
gp_debug_print(func_defs)
exec(func_defs)
-# Define an alias. rpvar is just a special case of rpvars where the args
-# list contains only one element.
+# Define an alias. rpvar is just a special case of rpvars where the args list contains only one element.
cmd_buf = "rpvar = rpvars"
gp_debug_print("\n" + cmd_buf + "\n")
exec(cmd_buf)
diff --git a/lib/gen_robot_ssh.py b/lib/gen_robot_ssh.py
index b936d61..b79daf6 100755
--- a/lib/gen_robot_ssh.py
+++ b/lib/gen_robot_ssh.py
@@ -1,8 +1,7 @@
#!/usr/bin/env python
r"""
-This module provides many valuable ssh functions such as sprint_connection,
-execute_ssh_command, etc.
+This module provides many valuable ssh functions such as sprint_connection, execute_ssh_command, etc.
"""
import sys
@@ -29,10 +28,9 @@
r"""
sprint data from the connection object to a string and return it.
- connection A connection object which is created by
- the SSHlibrary open_connection() function.
- indent The number of characters to indent the
- output.
+ connection A connection object which is created by the SSHlibrary open_connection()
+ function.
+ indent The number of characters to indent the output.
"""
buffer = gp.sindent("", indent)
@@ -60,13 +58,10 @@
r"""
sprint data from the connections list to a string and return it.
- connections A list of connection objects which are
- created by the SSHlibrary open_connection
- function. If this value is null, this
- function will populate with a call to the
- SSHlibrary get_connections() function.
- indent The number of characters to indent the
- output.
+ connections A list of connection objects which are created by the SSHlibrary
+ open_connection function. If this value is null, this function will
+ populate with a call to the SSHlibrary get_connections() function.
+ indent The number of characters to indent the output.
"""
if connections is None:
@@ -81,17 +76,14 @@
def find_connection(open_connection_args={}):
r"""
- Find connection that matches the given connection arguments and return
- connection object. Return False if no matching connection is found.
+ Find connection that matches the given connection arguments and return connection object. Return False
+ if no matching connection is found.
Description of argument(s):
- open_connection_args A dictionary of arg names and values which
- are legal to pass to the SSHLibrary
- open_connection function as parms/args.
- For a match to occur, the value for each
- item in open_connection_args must match
- the corresponding value in the connection
- being examined.
+ open_connection_args A dictionary of arg names and values which are legal to pass to the
+ SSHLibrary open_connection function as parms/args. For a match to occur,
+ the value for each item in open_connection_args must match the
+ corresponding value in the connection being examined.
"""
global sshlib
@@ -109,19 +101,16 @@
def login_ssh(login_args={},
max_login_attempts=5):
r"""
- Login on the latest open SSH connection. Retry on failure up to
- max_login_attempts.
+ Login on the latest open SSH connection. Retry on failure up to max_login_attempts.
The caller is responsible for making sure there is an open SSH connection.
Description of argument(s):
- login_args A dictionary containing the key/value
- pairs which are acceptable to the
- SSHLibrary login function as parms/args.
- At a minimum, this should contain a
- 'username' and a 'password' entry.
- max_login_attempts The max number of times to try logging in
- (in the event of login failures).
+ login_args A dictionary containing the key/value pairs which are acceptable to the
+ SSHLibrary login function as parms/args. At a minimum, this should
+ contain a 'username' and a 'password' entry.
+ max_login_attempts The max number of times to try logging in (in the event of login
+ failures).
"""
gp.lprint_executing()
@@ -145,15 +134,13 @@
re.match(r"No existing session", str(except_value)):
continue
else:
- # We don't tolerate any other error so break from loop and
- # re-raise exception.
+ # We don't tolerate any other error so break from loop and re-raise exception.
break
# If we get to this point, the login has worked and we can return.
gp.lprint_var(out_buf)
return
- # If we get to this point, the login has failed on all attempts so the
- # exception will be raised again.
+ # If we get to this point, the login has failed on all attempts so the exception will be raised again.
raise(except_value)
@@ -168,53 +155,39 @@
test_mode=None,
time_out=None):
r"""
- Run the given command in an SSH session and return the stdout, stderr and
- the return code.
+ Run the given command in an SSH session and return the stdout, stderr and the return code.
- If there is no open SSH connection, this function will connect and login.
- Likewise, if the caller has not yet logged in to the connection, this
- function will do the login.
+ If there is no open SSH connection, this function will connect and login. Likewise, if the caller has
+ not yet logged in to the connection, this function will do the login.
- NOTE: There is special handling when open_connection_args['alias'] equals
- "device_connection".
+ NOTE: There is special handling when open_connection_args['alias'] equals "device_connection".
- A write, rather than an execute_command, is done.
- Only stdout is returned (no stderr or rc).
- print_err, ignore_err and fork are not supported.
Description of arguments:
- cmd_buf The command string to be run in an SSH
- session.
- open_connection_args A dictionary of arg names and values which
- are legal to pass to the SSHLibrary
- open_connection function as parms/args.
- At a minimum, this should contain a 'host'
- entry.
- login_args A dictionary containing the key/value
- pairs which are acceptable to the
- SSHLibrary login function as parms/args.
- At a minimum, this should contain a
- 'username' and a 'password' entry.
- print_out If this is set, this function will print
- the stdout/stderr generated by the shell
- command.
- print_err If show_err is set, this function will
- print a standardized error report if the
- shell command returns non-zero.
- ignore_err Indicates that errors encountered on the
- sshlib.execute_command are to be ignored.
- fork Indicates that sshlib.start is to be used
- rather than sshlib.execute_command.
- quiet Indicates whether this function should run
- the pissuing() function which prints an
- "Issuing: <cmd string>" to stdout. This
- defaults to the global quiet value.
- test_mode If test_mode is set, this function will
- not actually run the command. This
- defaults to the global test_mode value.
- time_out The amount of time to allow for the
- execution of cmd_buf. A value of None
- means that there is no limit to how long
- the command may take.
+ cmd_buf The command string to be run in an SSH session.
+ open_connection_args A dictionary of arg names and values which are legal to pass to the
+ SSHLibrary open_connection function as parms/args. At a minimum, this
+ should contain a 'host' entry.
+ login_args A dictionary containing the key/value pairs which are acceptable to the
+ SSHLibrary login function as parms/args. At a minimum, this should
+ contain a 'username' and a 'password' entry.
+ print_out If this is set, this function will print the stdout/stderr generated by
+ the shell command.
+ print_err If show_err is set, this function will print a standardized error report
+ if the shell command returns non-zero.
+ ignore_err Indicates that errors encountered on the sshlib.execute_command are to be
+ ignored.
+ fork Indicates that sshlib.start is to be used rather than
+ sshlib.execute_command.
+ quiet Indicates whether this function should run the pissuing() function which
+ prints an "Issuing: <cmd string>" to stdout. This defaults to the global
+ quiet value.
+ test_mode If test_mode is set, this function will not actually run the command.
+ This defaults to the global test_mode value.
+ time_out The amount of time to allow for the execution of cmd_buf. A value of
+ None means that there is no limit to how long the command may take.
"""
gp.lprint_executing()
@@ -327,8 +300,7 @@
login_ssh(login_args)
continue
- # We do not handle any other RuntimeErrors so we will raise the
- # exception again.
+ # We do not handle any other RuntimeErrors so we will raise the exception again.
sshlib.close_all_connections()
gp.lprintn(traceback.format_exc())
raise(except_value)
diff --git a/lib/gen_robot_valid.py b/lib/gen_robot_valid.py
index 3e4a0cd..264393b 100755
--- a/lib/gen_robot_valid.py
+++ b/lib/gen_robot_valid.py
@@ -1,8 +1,7 @@
#!/usr/bin/env python
r"""
-This module provides validation functions like valid_value(), valid_integer(),
-etc. for robot programs.
+This module provides validation functions like valid_value(), valid_integer(), etc. for robot programs.
"""
import re
@@ -17,14 +16,11 @@
r"""
Validate the robot variable name and return its value.
- If the variable is undefined, this function will print an error message
- and call BuiltIn().fail().
+ If the variable is undefined, this function will print an error message and call BuiltIn().fail().
Description of arguments():
- var_name The name of the robot variable (e.g.
- "var1"). Do not include "${}" (e.g.
- "${var1}". Just provide the simple name
- of the variable.
+ var_name The name of the robot variable (e.g. "var1"). Do not include "${}" (e.g.
+ "${var1}". Just provide the simple name of the variable.
"""
# Note: get_variable_value() seems to have no trouble with local variables.
@@ -40,25 +36,20 @@
def valid_init(var_name, *args, **kwargs):
r"""
- Do initialization for variable validation and return var_name, args and
- kwargs.
+ Do initialization for variable validation and return var_name, args and kwargs.
- This function is to be called by all of the various validation functions
- in this module.
+ This function is to be called by all of the various validation functions in this module.
This function is designed solely for use by other functions in this file.
Description of argument(s):
var_name The name of the variable to be validated.
- args The positional arguments to be passed to a
- validation function.
- kwargs The keyword arguments to be passed to a
- validation function.
+ args The positional arguments to be passed to a validation function.
+ kwargs The keyword arguments to be passed to a validation function.
"""
var_value = valid_var_name(var_name)
- # Convert python string object definitions to objects (useful for robot
- # callers).
+ # Convert python string object definitions to objects (useful for robot callers).
args = fa.args_to_objects(args)
kwargs = fa.args_to_objects(kwargs)
return var_value, args, kwargs
@@ -81,8 +72,7 @@
BuiltIn().fail(error_message)
-# The docstring header will be pre-pended to each validation function's
-# existing docstring.
+# The docstring header will be pre-pended to each validation function's existing docstring.
docstring_header = \
r"""
Fail if the variable named by var_name is invalid.
@@ -95,16 +85,14 @@
This function is designed solely for use by other functions in this file.
- The caller should pass a docstring from a gen_valid.py validation
- function. This docstring will be changed to make a suitable docstring for
- this module's corresponding validation function.
+ The caller should pass a docstring from a gen_valid.py validation function. This docstring will be
+ changed to make a suitable docstring for this module's corresponding validation function.
For example:
- Let's suppose that gen_valid.py has a function called "valid_value()".
- This module could make the following call to essentially copy gen_valid's
- "valid_value()" function, modify it and then assign it to the local
- version of the valid_value() function.
+ Let's suppose that gen_valid.py has a function called "valid_value()". This module could make the
+ following call to essentially copy gen_valid's "valid_value()" function, modify it and then assign it to
+ the local version of the valid_value() function.
valid.__doc__ = customize_doc_string(gv.valid.__doc__)
@@ -127,12 +115,10 @@
return "\n".join(doc_string)
-# All of the following functions are robot wrappers for the equivalent
-# functions defined in gen_valid.py. Note that the only difference between
-# any two of these locally defined functions is the function name and the
-# gv.<function name> which they call. Also, note that the docstring for each
-# is created by modifying the docstring from the supporting gen_valid.py
-# function.
+# All of the following functions are robot wrappers for the equivalent functions defined in gen_valid.py.
+# Note that the only difference between any two of these locally defined functions is the function name and
+# the gv.<function name> which they call. Also, note that the docstring for each is created by modifying the
+# docstring from the supporting gen_valid.py function.
def valid_type(var_name, *args, **kwargs):
@@ -222,8 +208,8 @@
process_error_message(error_message)
-# Modify the validation function docstrings by calling customize_doc_string
-# for each function in the func_names list.
+# Modify the validation function docstrings by calling customize_doc_string for each function in the
+# func_names list.
func_names = [
"valid_type", "valid_value", "valid_range", "valid_integer",
"valid_dir_path", "valid_file_path", "valid_path", "valid_list",
diff --git a/lib/host.tcl b/lib/host.tcl
index 365847e..21d352a 100755
--- a/lib/host.tcl
+++ b/lib/host.tcl
@@ -1,25 +1,22 @@
#!/usr/bin/wish
-# This file provides valuable host and IP manipulation procedures such as
-# get_host_name_ip, etc.
+# This file provides valuable host and IP manipulation procedures such as get_host_name_ip, etc.
my_source [list cmd.tcl data_proc.tcl]
proc get_host_name_ip {host {quiet 1}} {
- # Get the host name, short host name and the IP address and return them as
- # a list.
- # If this procedure is unable to get the requested information, it will
- # print an error message to stderr and return blank values.
+ # Get the host name, short host name and the IP address and return them as a list.
+ # If this procedure is unable to get the requested information, it will print an error message to stderr
+ # and return blank values.
# Example call:
# lassign [get_host_name_ip $host] host_name short_host_name ip_address
# Description of argument(s):
# host The host name or IP address to be obtained.
- # quiet Indicates whether status information
- # should be printed.
+ # quiet Indicates whether status information should be printed.
set print_output [expr !$quiet]
lassign [cmd_fnc "host $host" "${quiet}" "" "${print_output}"] rc out_buf
diff --git a/lib/opt.tcl b/lib/opt.tcl
index 50c8309..e33bacd 100755
--- a/lib/opt.tcl
+++ b/lib/opt.tcl
@@ -1,29 +1,24 @@
#!/usr/bin/wish
-# This file provides many valuable parm and argument processing procedures
-# such as longoptions, pos_parms, gen_get_options, etc.
+# This file provides many valuable parm and argument processing procedures such as longoptions, pos_parms,
+# gen_get_options, etc.
my_source [list escape.tcl data_proc.tcl print.tcl]
proc get_arg_req { opt_name } {
- # Determine whether the given opt_name is "optional", "required" or
- # "not_allowed" and return that result.
+ # Determine whether the given opt_name is "optional", "required" or "not_allowed" and return that result.
- # Note: This procedure assumes that global list longoptions has been
- # initialized via a call to the longoptions procedure.
+ # Note: This procedure assumes that global list longoptions has been initialized via a call to the
+ # longoptions procedure.
# Description of argument(s):
- # opt_name The name of the option including its
- # requirement indicator as accepted by the
- # bash getopt longoptions parameter: No
- # colon means the option takes no argument,
- # one colon means the option requires an
- # argument and two colons indicate that an
- # argument is optional (the value of the
- # option will be 1 if no argument is
- # specified.
+ # opt_name The name of the option including its requirement indicator as accepted by
+ # the bash getopt longoptions parameter: No colon means the option takes no
+ # argument, one colon means the option requires an argument and two colons
+ # indicate that an argument is optional (the value of the option will be 1
+ # if no argument is specified.
global longoptions
@@ -40,29 +35,25 @@
proc longoptions { args } {
- # Populate the global longoptions list and set global option variable
- # defaults.
+ # Populate the global longoptions list and set global option variable defaults.
# Description of argument(s):
- # args Each arg is comprised of 1) the name of
- # the option 2) zero, one or 2 colons to
- # indicate whether the corresponding
- # argument value is a) not required, b)
- # required or c) optional 3) Optionally, an
- # equal sign followed by a default value for
- # the parameter.
+ # args Each arg is comprised of 1) the name of the option 2) zero, one or 2
+ # colons to indicate whether the corresponding argument value is a) not
+ # required, b) required or c) optional 3) Optionally, an equal sign
+ # followed by a default value for the parameter.
# Example usage:
# longoptions parm1 parm2: parm3:: test_mode:=0 quiet:=0
global longoptions
- # Note: Because this procedure manipulates global variables, we use the
- # "_opt_<varname>_" format to minimize the possibility of naming collisions.
+ # Note: Because this procedure manipulates global variables, we use the "_opt_<varname>_" format to
+ # minimize the possibility of naming collisions.
set _opt_debug_ 0
foreach _opt_arg_ $args {
- # Create an option record which is a 2-element list consisting of the
- # option specification and a possible default value. Example:;
+ # Create an option record which is a 2-element list consisting of the option specification and a
+ # possible default value. Example:;
# opt_rec:
# opt_rec[0]: test_mode:
# opt_rec[1]: 0
@@ -77,12 +68,11 @@
set _opt_default_value_ [lindex $_opt_rec_ 1]
set _opt_arg_req_ [get_arg_req $_opt_name_]
if { $_opt_arg_req_ == "not_allowed" && $_opt_default_value_ == "" } {
- # If this parm takes no arg and no default was specified by the user,
- # we will set the default to 0.
+ # If this parm takes no arg and no default was specified by the user, we will set the default to 0.
set _opt_default_value_ 0
}
- # Set a global variable whose name is identical to the option name. Set
- # the default value if there is one.
+ # Set a global variable whose name is identical to the option name. Set the default value if there is
+ # one.
set _opt_cmd_buf_ "global ${_opt_name_}"
if { $_opt_debug_ } { print_issuing $_opt_cmd_buf_ }
eval $_opt_cmd_buf_
@@ -99,9 +89,8 @@
# Populate the global pos_parms list and set global option variable defaults.
# Description of argument(s):
- # args Each arg is comprised of the name of a
- # positional parm and a possible initial
- # value.
+ # args Each arg is comprised of the name of a positional parm and a possible
+ # initial value.
# Example usage:
# pos_parms user_name=mike
@@ -109,13 +98,13 @@
global pos_parms
set pos_parms [list]
- # Note: Because this procedure manipulates global variables, we use the
- # "_opt_<varname>_" format to minimize the possibility of naming collisions.
+ # Note: Because this procedure manipulates global variables, we use the "_opt_<varname>_" format to
+ # minimize the possibility of naming collisions.
set _opt_debug_ 0
foreach _opt_arg_ $args {
if { $_opt_debug_ } { print_var _opt_arg_ }
- # Create an option record which is a 2-element list consisting of the
- # option specification and a possible default value. Example:;
+ # Create an option record which is a 2-element list consisting of the option specification and a
+ # possible default value. Example:;
# opt_rec:
# opt_rec[0]: test_mode:
# opt_rec[1]: 0
@@ -129,8 +118,8 @@
# Get the option's default value, if any.
set _opt_parm_default_value_ [lindex $_opt_parm_rec_ 1]
if { $_opt_debug_ } { print_var _opt_parm_default_value_ }
- # Set a global variable whose name is identical to the option name. Set
- # the default value if there is one.
+ # Set a global variable whose name is identical to the option name. Set the default value if there is
+ # one.
set _opt_cmd_buf_ "global ${_opt_parm_name_} ; set ${_opt_parm_name_}"
append _opt_cmd_buf_ " {${_opt_parm_default_value_}}"
if { $_opt_debug_ } { pissuing $_opt_cmd_buf_ }
@@ -142,22 +131,18 @@
proc gen_get_options { argv } {
- # Get the command line options/arguments and use them to set the
- # corresponding global option variable names.
+ # Get the command line options/arguments and use them to set the corresponding global option variable names.
- # Note: This procedure assumes that global list longoptions has been
- # initialized via a call to the longoptions procedure and that global
- # pos_parms has been initialized via a call to the pos_parms procdure.
- # These data structures indicates what options and arguments are supported
- # by the calling program.
+ # Note: This procedure assumes that global list longoptions has been initialized via a call to the
+ # longoptions procedure and that global pos_parms has been initialized via a call to the pos_parms
+ # procdure. These data structures indicates what options and arguments are supported by the calling
+ # program.
- # Note: If the last var_name in pos_parms ends in "_list", then the caller
- # can specify as many parms as they desire and they will all be appended to
- # the variable in question.
+ # Note: If the last var_name in pos_parms ends in "_list", then the caller can specify as many parms as
+ # they desire and they will all be appended to the variable in question.
# Description of argument(s):
- # argv The argv array that is set for this
- # program.
+ # argv The argv array that is set for this program.
# Example call:
# gen_get_options $argv
@@ -166,8 +151,8 @@
global pos_parms
global program_name
- # Note: Because this procedure manipulates global variables, we use the
- # "_opt_<varname>_" format to minimize the possibility of naming collisions.
+ # Note: Because this procedure manipulates global variables, we use the "_opt_<varname>_" format to
+ # minimize the possibility of naming collisions.
set _opt_debug_ 0
set _opt_len_pos_parms_ [llength $pos_parms]
@@ -178,17 +163,14 @@
print_var _opt_len_pos_parms_
}
- # Rather than write the algorithm from scratch, we will call upon the bash
- # getopt program to help us. This program has several advantages:
+ # Rather than write the algorithm from scratch, we will call upon the bash getopt program to help us.
+ # This program has several advantages:
# - It will reject illegal options
- # - It supports different posix input styles (e.g. -option <arg> vs
- # --option=<arg>).
- # - It allows the program's caller to abbreviate option names provided that
- # there is no ambiguity.
+ # - It supports different posix input styles (e.g. -option <arg> vs --option=<arg>).
+ # - It allows the program's caller to abbreviate option names provided that there is no ambiguity.
- # Convert curly braces to single quotes. This includes escaping existing
- # quotes in the argv string. This will allow us to use the result in a bash
- # command string. Example: {--parm3=Kathy's cat} will become
+ # Convert curly braces to single quotes. This includes escaping existing quotes in the argv string. This
+ # will allow us to use the result in a bash command string. Example: {--parm3=Kathy's cat} will become
# '--parm3=Kathy'\''s cat'.
if { $_opt_debug_ } { print_var argv }
set _opt_bash_args_ [curly_braces_to_quotes $argv]
@@ -327,19 +309,14 @@
# Print help text for the given option.
# Description of argument(s):
- # option The option for which help text should be
- # printed. This value should include a
- # leading "--" to indicate that this is an
- # optional rather than a positional parm.
- # data_desc A description of the data (e.g. "dir
- # path", "1,0", etc.)0
- # print_default Indicates whether the current value of the
- # global variable representing the option is
- # to be printed as a default value. For
- # example, if the option value is "--parm1",
- # global value parm1 is "no" and
- # print_default is set, the following phrase
- # will be appended to the help text: The
+ # option The option for which help text should be printed. This value should
+ # include a leading "--" to indicate that this is an optional rather than a
+ # positional parm.
+ # data_desc A description of the data (e.g. "dir path", "1,0", etc.)0
+ # print_default Indicates whether the current value of the global variable representing
+ # the option is to be printed as a default value. For example, if the
+ # option value is "--parm1", global value parm1 is "no" and print_default
+ # is set, the following phrase will be appended to the help text: The
# default value is "no".
# width The width of the arguments column.
@@ -407,11 +384,9 @@
# Print general help text based on user's pos_parms and longoptions.
- # Note: To use this procedure, the user must create a global help_dict
- # containing entries for each of their options and one for the program as a
- # whole. The keys of this dictionary are the option names and the values
- # are lists whose values map to arguments from the print_option_help
- # procedure:
+ # Note: To use this procedure, the user must create a global help_dict containing entries for each of
+ # their options and one for the program as a whole. The keys of this dictionary are the option names and
+ # the values are lists whose values map to arguments from the print_option_help procedure:
# - help_text
# - data_desc (optional)
# - print_default (1 or 0 - default is 1)
@@ -457,8 +432,7 @@
puts ""
puts "positional arguments:"
foreach option $pos_parms {
- # Retrieve the print_option_help parm values from the help_dict and
- # call print_option_help.
+ # Retrieve the print_option_help parm values from the help_dict and call print_option_help.
set help_entry [dict get $help_dict ${option}]
set help_text [lindex $help_entry 0]
set data_desc [lindex $help_entry 1]
@@ -473,8 +447,7 @@
puts "optional arguments:"
foreach option $longoptions {
set option [string trim $option ":"]
- # Retrieve the print_option_help parm values from the help_dict and
- # call print_option_help.
+ # Retrieve the print_option_help parm values from the help_dict and call print_option_help.
set help_entry [dict get $help_dict ${option}]
set help_text [lindex $help_entry 0]
set data_desc [lindex $help_entry 1]
@@ -513,13 +486,11 @@
proc gen_pre_validation {} {
- # Do generic post-validation processing. By "post", we mean that this is
- # to be called from a validation function after the caller has done any
- # validation desired. If the calling program passes exit_function and
- # signal_handler parms, this function will register them. In other words,
- # it will make the signal_handler functions get called for SIGINT and
- # SIGTERM and will make the exit_function function run prior to the
- # termination of the program.
+ # Do generic post-validation processing. By "post", we mean that this is to be called from a validation
+ # function after the caller has done any validation desired. If the calling program passes exit_function
+ # and signal_handler parms, this function will register them. In other words, it will make the
+ # signal_handler functions get called for SIGINT and SIGTERM and will make the exit_function function run
+ # prior to the termination of the program.
# Make all program option global variables available to the calling function.
uplevel global_program_options
@@ -529,13 +500,11 @@
proc gen_post_validation {} {
- # Do generic post-validation processing. By "post", we mean that this is
- # to be called from a validation function after the caller has done any
- # validation desired. If the calling program passes exit_function and
- # signal_handler parms, this function will register them. In other words,
- # it will make the signal_handler functions get called for SIGINT and
- # SIGTERM and will make the exit_function function run prior to the
- # termination of the program.
+ # Do generic post-validation processing. By "post", we mean that this is to be called from a validation
+ # function after the caller has done any validation desired. If the calling program passes exit_function
+ # and signal_handler parms, this function will register them. In other words, it will make the
+ # signal_handler functions get called for SIGINT and SIGTERM and will make the exit_function function run
+ # prior to the termination of the program.
trap { exit_proc } [list SIGTERM SIGINT]
diff --git a/lib/print.tcl b/lib/print.tcl
index 98cd051..3959088 100755
--- a/lib/print.tcl
+++ b/lib/print.tcl
@@ -1,7 +1,6 @@
#!/usr/bin/wish
-# This file provides many valuable print procedures such as sprint_var,
-# sprint_time, sprint_error, etc.
+# This file provides many valuable print procedures such as sprint_var, sprint_time, sprint_error, etc.
my_source [list data_proc.tcl call_stack.tcl]
@@ -9,14 +8,12 @@
package require Expect
-# Setting the following variables for use both inside this file and by
-# programs sourcing this file.
+# Setting the following variables for use both inside this file and by programs sourcing this file.
set program_path $argv0
set program_dir_path "[file dirname $argv0]/"
set program_name "[file tail $argv0]"
-# Some procedures (e.g. sprint_pgm_header) need a program name value that
-# looks more like a valid variable name. Therefore, we'll swap out odd
-# characters (like ".") for underscores.
+# Some procedures (e.g. sprint_pgm_header) need a program name value that looks more like a valid variable
+# name. Therefore, we'll swap out odd characters (like ".") for underscores.
regsub {\.} $program_name "_" pgm_name_var_name
# Initialize some time variables used in procedures in this file.
@@ -25,36 +22,33 @@
proc calc_wrap_stack_ix_adjust {} {
- # Calculate and return a number which can be used as an offset into the
- # call stack for wrapper procedures.
+ # Calculate and return a number which can be used as an offset into the call stack for wrapper procedures.
- # NOTE: This procedure is designed expressly to work with this file's print
- # procedures scheme (i.e. print_x is a wrapper for sprint_x, etc.). In
- # other words, this procedure may not be well-suited for general use.
+ # NOTE: This procedure is designed expressly to work with this file's print procedures scheme (i.e.
+ # print_x is a wrapper for sprint_x, etc.). In other words, this procedure may not be well-suited for
+ # general use.
- # Get a list of the procedures in the call stack beginning with our
- # immediate caller on up to the top-level caller.
+ # Get a list of the procedures in the call stack beginning with our immediate caller on up to the
+ # top-level caller.
set call_stack [get_call_stack -2]
# The first stack entry is our immediate caller.
set caller [lindex $call_stack 0]
# Remove first entry from stack.
set call_stack [lreplace $call_stack 0 0]
- # Strip any leading "s" to arrive at base_caller name (e.g. the
- # corresponding base name for "sprint_var" would be "print_var").
+ # Strip any leading "s" to arrive at base_caller name (e.g. the corresponding base name for "sprint_var"
+ # would be "print_var").
set base_caller [string trimleft $caller s]
- # Account for alias print procedures which have "p" vs "print_" (e.g. pvar
- # vs print_var).
+ # Account for alias print procedures which have "p" vs "print_" (e.g. pvar vs print_var).
regsub "print_" $base_caller "p" alias_base_caller
# Initialize the stack_ix_adjust value.
set stack_ix_adjust 0
- # Note: print_vars|pvars is a special case so we add it explicitly to the
- # regex below.
+ # Note: print_vars|pvars is a special case so we add it explicitly to the regex below.
set regex ".*(${base_caller}|${alias_base_caller}|print_vars|pvars)$"
foreach proc_name $call_stack {
- # For every remaining stack item that looks like a wrapper (i.e. matches
- # our regex), we increment the stack_ix_adjust.
+ # For every remaining stack item that looks like a wrapper (i.e. matches our regex), we increment the
+ # stack_ix_adjust.
if { [regexp -expanded $regex $proc_name]} {
incr stack_ix_adjust
continue
@@ -68,25 +62,23 @@
}
-# hidden_text is a list of passwords which are to be replaced with asterisks
-# by print procedures defined in this file.
+# hidden_text is a list of passwords which are to be replaced with asterisks by print procedures defined in
+# this file.
set hidden_text [list]
# password_regex is created from the contents of the hidden_text list above.
set password_regex ""
proc register_passwords {args} {
- # Register one or more passwords which are to be hidden in output produced
- # by the print procedures in this file.
+ # Register one or more passwords which are to be hidden in output produced by the print procedures in this
+ # file.
# Note: Blank password values are NOT registered. They are simply ignored.
# Description of argument(s):
- # args One or more password values. If a given
- # password value is already registered, this
- # procedure will simply ignore it, i.e.
- # there will be no duplicate values in the
- # hidden_text list.
+ # args One or more password values. If a given password value is already
+ # registered, this procedure will simply ignore it, i.e. there will be no
+ # duplicate values in the hidden_text list.
global hidden_text
global password_regex
@@ -108,14 +100,12 @@
proc replace_passwords {buffer} {
- # Replace all registered password found in buffer with a string of
- # asterisks and return the result.
+ # Replace all registered password found in buffer with a string of asterisks and return the result.
# Description of argument(s):
# buffer The string to be altered and returned.
- # Note: If environment variable GEN_PRINT_DEBUG is set, this procedure
- # will do nothing.
+ # Note: If environment variable GEN_PRINT_DEBUG is set, this procedure will do nothing.
global env
if { [get_var ::env(GEN_PRINT_DEBUG) 0] } { return $buffer }
@@ -141,9 +131,8 @@
# Description of argument(s):
# cmd_buf The command string to be run.
- # iterations The number of times to run the command
- # string. Typically, more iterations yields
- # more accurate results.
+ # iterations The number of times to run the command string. Typically, more
+ # iterations yields more accurate results.
print_issuing $cmd_buf
set result [time {uplevel 1 $cmd_buf} $iterations]
@@ -160,18 +149,16 @@
}
-# If environment variable "GEN_PRINT_DEBUG" is set, this module will output
-# debug data. This is primarily intended for the developer of this module.
+# If environment variable "GEN_PRINT_DEBUG" is set, this module will output debug data. This is primarily
+# intended for the developer of this module.
set GEN_PRINT_DEBUG [get_var ::env(GEN_PRINT_DEBUG) 0]
-# The user can set the following environment variables to influence the
-# output from print_time and print_var procedures. See the prologs of those
-# procedures for details.
+# The user can set the following environment variables to influence the output from print_time and print_var
+# procedures. See the prologs of those procedures for details.
set NANOSECONDS [get_var ::env(NANOSECONDS) 0]
set SHOW_ELAPSED_TIME [get_var ::env(SHOW_ELAPSED_TIME) 0]
-# _gtp_default_print_var_width_ is adjusted based on NANOSECONDS and
-# SHOW_ELAPSED_TIME.
+# _gtp_default_print_var_width_ is adjusted based on NANOSECONDS and SHOW_ELAPSED_TIME.
if { $NANOSECONDS } {
set _gtp_default_print_var_width_ 36
set width_incr 14
@@ -181,20 +168,20 @@
}
if { $SHOW_ELAPSED_TIME } {
incr _gtp_default_print_var_width_ $width_incr
- # Initializing _sprint_time_last_seconds_ which is a global value to
- # remember the clock seconds from the last time sprint_time was called.
+ # Initializing _sprint_time_last_seconds_ which is a global value to remember the clock seconds from the
+ # last time sprint_time was called.
set _gtp_sprint_time_last_micro_seconds_ [clock microseconds]
}
-# tcl_precision is a built-in Tcl variable that specifies the number of
-# digits to generate when converting floating-point values to strings.
+# tcl_precision is a built-in Tcl variable that specifies the number of digits to generate when converting
+# floating-point values to strings.
set tcl_precision 17
proc sprint { { buffer {} } } {
# Simply return the user's buffer.
- # This procedure is used by the qprint and dprint functions defined
- # dynamically below, i.e. it would not normally be called for general use.
+ # This procedure is used by the qprint and dprint functions defined dynamically below, i.e. it would not
+ # normally be called for general use.
# Description of arguments.
# buffer This will be returned to the caller.
@@ -207,8 +194,8 @@
proc sprintn { { buffer {} } } {
# Simply return the user's buffer plus a trailing line feed..
- # This procedure is used by the qprintn and dprintn functions defined
- # dynamically below, i.e. it would not normally be called for general use.
+ # This procedure is used by the qprintn and dprintn functions defined dynamically below, i.e. it would not
+ # normally be called for general use.
# Description of arguments.
# buffer This will be returned to the caller.
@@ -243,38 +230,29 @@
# #(CDT) 2016/08/03 17:12:05 - Hi.
- # The following environment variables will affect the formatting as
- # described:
- # NANOSECONDS This will cause the time stamps to be
- # precise to the microsecond (Yes, it
- # probably should have been named
- # MICROSECONDS but the convention was set
- # long ago so we're sticking with it).
- # Example of the output when environment
- # variable NANOSECONDS=1.
+ # The following environment variables will affect the formatting as described:
+ # NANOSECONDS This will cause the time stamps to be precise to the microsecond (Yes, it
+ # probably should have been named MICROSECONDS but the convention was set
+ # long ago so we're sticking with it). Example of the output when
+ # environment variable NANOSECONDS=1.
# #(CDT) 2016/08/03 17:16:25.510469 - Hi.
- # SHOW_ELAPSED_TIME This will cause the elapsed time to be
- # included in the output. This is the
- # amount of time that has elapsed since the
- # last time this procedure was called. The
- # precision of the elapsed time field is
- # also affected by the value of the
- # NANOSECONDS environment variable. Example
- # of the output when environment variable
- # NANOSECONDS=0 and SHOW_ELAPSED_TIME=1.
+ # SHOW_ELAPSED_TIME This will cause the elapsed time to be included in the output. This is
+ # the amount of time that has elapsed since the last time this procedure
+ # was called. The precision of the elapsed time field is also affected by
+ # the value of the NANOSECONDS environment variable. Example of the output
+ # when environment variable NANOSECONDS=0 and SHOW_ELAPSED_TIME=1.
# #(CDT) 2016/08/03 17:17:40 - 0 - Hi.
- # Example of the output when environment variable NANOSECONDS=1 and
- # SHOW_ELAPSED_TIME=1.
+ # Example of the output when environment variable NANOSECONDS=1 and SHOW_ELAPSED_TIME=1.
# #(CDT) 2016/08/03 17:18:47.317339 - 0.000046 - Hi.
# Description of argument(s).
- # buffer A string string whhich is to be appended
- # to the formatted time string and returned.
+ # buffer A string string whhich is to be appended to the formatted time string and
+ # returned.
global NANOSECONDS
global _gtp_sprint_time_last_micro_seconds_
@@ -326,8 +304,7 @@
# Return the value of sprint_time + a line feed.
# Description of argument(s):
- # args All args are passed directly to
- # subordinate function, sprint_time. See
+ # args All args are passed directly to subordinate function, sprint_time. See
# that function's prolog for details.
return [sprint_time {*}$args]\n
@@ -340,8 +317,7 @@
# Return a standardized error string which includes the callers buffer text.
# Description of argument(s):
- # buffer Text to be returned as part of the error
- # message.
+ # buffer Text to be returned as part of the error message.
return [sprint_time "**ERROR** $buffer"]
@@ -350,11 +326,9 @@
proc sprint_varx { var_name var_value { indent 0 } { width {} } { hex 0 } } {
- # Return the name and value of the variable named in var_name in a
- # formatted way.
+ # Return the name and value of the variable named in var_name in a formatted way.
- # This procedure will visually align the output to look good next to
- # print_time output.
+ # This procedure will visually align the output to look good next to print_time output.
# Example:
@@ -368,8 +342,7 @@
# print_varx first_name $first_name 2
# print_varx age $age 2
- # With environment variables NANOSECONDS and SHOW_ELAPSED_TIME both set,
- # the following output is produced:
+ # With environment variables NANOSECONDS and SHOW_ELAPSED_TIME both set, the following output is produced:
# #(CST) 2017/12/14 16:38:28.259480 - 0.000651 - Initializing variables.
# last_name: Montana
@@ -377,23 +350,15 @@
# age: 50
# Description of argument(s):
- # var_name The name of the variable whose name and
- # value are to be printed.
+ # var_name The name of the variable whose name and value are to be printed.
# var_value The value to be printed.
- # indent The number of spaces to indent each line
- # of output.
- # width The width of the column containing the
- # variable name. By default this will align
- # with the print_time text (see example
- # above).
- # hex Indicates that the variable value is to be
- # printed in hexedecimal format. This is
- # only valid if the variable value is an
- # integer. If the variable is NOT an
- # integer and is blank, this will be
- # interpreted to mean "print the string
- # '<blank>', rather than an actual blank
- # value".
+ # indent The number of spaces to indent each line of output.
+ # width The width of the column containing the variable name. By default this
+ # will align with the print_time text (see example above).
+ # hex Indicates that the variable value is to be printed in hexedecimal format.
+ # This is only valid if the variable value is an integer. If the variable
+ # is NOT an integer and is blank, this will be interpreted to mean "print
+ # the string '<blank>', rather than an actual blank value".
# Note: This procedure relies on global var _gtp_default_print_var_width_
@@ -428,19 +393,16 @@
proc sprint_var { var_name args } {
- # Return the name and value of the variable named in var_name in a
- # formatted way.
+ # Return the name and value of the variable named in var_name in a formatted way.
- # This procedure will visually align the output to look good next to
- # print_time output.
+ # This procedure will visually align the output to look good next to print_time output.
- # Note: This procedure is the equivalent of sprint_varx with one
- # difference: This function will figure out the value of the named variable
- # whereas sprint_varx expects you to pass the value. This procedure in fact
- # calls sprint_varx to do its work.
+ # Note: This procedure is the equivalent of sprint_varx with one difference: This function will figure
+ # out the value of the named variable whereas sprint_varx expects you to pass the value. This procedure in
+ # fact calls sprint_varx to do its work.
- # Note: This procedure will detect whether var_name is an array and print
- # it accordingly (see the second example below).
+ # Note: This procedure will detect whether var_name is an array and print it accordingly (see the second
+ # example below).
# Example:
@@ -454,8 +416,7 @@
# print_var first_name 2
# print_var age 2
- # With environment variables NANOSECONDS and SHOW_ELAPSED_TIME both set,
- # the following output is produced:
+ # With environment variables NANOSECONDS and SHOW_ELAPSED_TIME both set, the following output is produced:
# #(CST) 2017/12/14 16:38:28.259480 - 0.000651 - Initializing variables.
# last_name: Montana
@@ -474,16 +435,13 @@
# data(1): horse
# Description of argument(s):
- # var_name The name of the variable whose name and
- # value are to be printed.
- # args The args understood by sprint_varx (after
- # var_name and var_value). See
+ # var_name The name of the variable whose name and value are to be printed.
+ # args The args understood by sprint_varx (after var_name and var_value). See
# sprint_varx's prolog for details.
# Note: This procedure relies on global var _gtp_default_print_var_width_
- # Determine who our caller is and therefore what upvar_level to use to get
- # var_value.
+ # Determine who our caller is and therefore what upvar_level to use to get var_value.
set stack_ix_adjust [calc_wrap_stack_ix_adjust]
set upvar_level [expr $stack_ix_adjust + 1]
upvar $upvar_level $var_name var_value
@@ -509,8 +467,7 @@
return $buffer
}
- # If var_value is not defined, catch the error and print its value as
- # "variable not set".
+ # If var_value is not defined, catch the error and print its value as "variable not set".
if {[catch {set buffer [sprint_varx $var_name $var_value {*}$args]} error_text options]} {
set regex ":\[ \]no\[ \]such\[ \]variable"
if { [regexp -expanded ${regex} ${error_text}]} {
@@ -528,22 +485,18 @@
proc sprint_list { var_name args } {
- # Return the name and value of the list variable named in var_name in a
- # formatted way.
+ # Return the name and value of the list variable named in var_name in a formatted way.
# This procedure is the equivalent of sprint_var but for lists.
# Description of argument(s):
- # var_name The name of the variable whose name and
- # value are to be printed.
- # args The args understood by sprint_varx (after
- # var_name and var_value). See
+ # var_name The name of the variable whose name and value are to be printed.
+ # args The args understood by sprint_varx (after var_name and var_value). See
# sprint_varx's prolog for details.
- # Note: In TCL, there is no way to determine that a variable represents a
- # list vs a string, etc. It is up to the programmer to decide how the data
- # is to be interpreted. Thus the need for procedures such as this one.
- # Consider the following code:
+ # Note: In TCL, there is no way to determine that a variable represents a list vs a string, etc. It is up
+ # to the programmer to decide how the data is to be interpreted. Thus the need for procedures such as this
+ # one. Consider the following code:
# set my_list {one two three}
# print_var my_list
@@ -556,9 +509,8 @@
# my_list[1]: two
# my_list[2]: three
- # As far as print_var is concerned, my_list is a string and is printed
- # accordingly. By using print_list, the programmer is asking to have the
- # output shown as a list with list indices, etc.
+ # As far as print_var is concerned, my_list is a string and is printed accordingly. By using print_list,
+ # the programmer is asking to have the output shown as a list with list indices, etc.
# Determine who our caller is and therefore what upvar_level to use.
set stack_ix_adjust [calc_wrap_stack_ix_adjust]
@@ -586,38 +538,32 @@
proc sprint_dict { var_name args } {
- # Return the name and value of the dictionary variable named in var_name in
- # a formatted way.
+ # Return the name and value of the dictionary variable named in var_name in a formatted way.
# This procedure is the equivalent of sprint_var but for dictionaries.
# Description of argument(s):
- # var_name The name of the variable whose name and
- # value are to be printed.
- # args The args understood by sprint_varx (after
- # var_name and var_value). See
+ # var_name The name of the variable whose name and value are to be printed.
+ # args The args understood by sprint_varx (after var_name and var_value). See
# sprint_varx's prolog for details.
- # Note: In TCL, there is no way to determine that a variable represents a
- # dictionary vs a string, etc. It is up to the programmer to decide how the
- # data is to be interpreted. Thus the need for procedures such as this one.
- # Consider the following code:
+ # Note: In TCL, there is no way to determine that a variable represents a dictionary vs a string, etc. It
+ # is up to the programmer to decide how the data is to be interpreted. Thus the need for procedures such
+ # as this one. Consider the following code:
# set my_dict [dict create first Joe last Montana age 50]
# print_var my_dict
# print_dict my_dict
# Output from aforementioned code:
- # my_dict: first Joe last Montana
- # age 50
+ # my_dict: first Joe last Montana age 50
# my_dict:
# my_dict[first]: Joe
# my_dict[last]: Montana
# my_dict[age]: 50
- # As far as print_var is concerned, my_dict is a string and is printed
- # accordingly. By using print_dict, the programmer is asking to have the
- # output shown as a dictionary with dictionary keys/values, etc.
+ # As far as print_var is concerned, my_dict is a string and is printed accordingly. By using print_dict,
+ # the programmer is asking to have the output shown as a dictionary with dictionary keys/values, etc.
# Determine who our caller is and therefore what upvar_level to use.
set stack_ix_adjust [calc_wrap_stack_ix_adjust]
@@ -646,11 +592,10 @@
# Sprint the values of one or more variables.
# Description of arg(s):
- # args: A list of variable names to be printed. The first argument in the
- # arg list found to be an integer (rather than a variable name) will be
- # interpreted to be first of several possible sprint_var arguments (e.g.
- # indent, width, hex). See the prologue for sprint_var above for
- # descriptions of this variables.
+ # args: A list of variable names to be printed. The first argument in the arg list found to be an
+ # integer (rather than a variable name) will be interpreted to be first of several possible sprint_var
+ # arguments (e.g. indent, width, hex). See the prologue for sprint_var above for descriptions of this
+ # variables.
# Example usage:
# set var1 "hello"
@@ -686,15 +631,12 @@
# Return a string of dashes to the caller.
# Description of argument(s):
- # indent The number of characters to indent the
- # output.
+ # indent The number of characters to indent the output.
# width The width of the string of dashes.
- # line_feed Indicates whether the output should end
- # with a line feed.
- # char The character to be repeated in the output
- # string. In other words, you can call on
- # this function to print a string of any
- # character (e.g. "=", "_", etc.).
+ # line_feed Indicates whether the output should end with a line feed.
+ # char The character to be repeated in the output string. In other words, you
+ # can call on this function to print a string of any character (e.g. "=",
+ # "_", etc.).
set_var_default indent 0
set_var_default width 80
@@ -714,8 +656,7 @@
# #(CST) 2017/11/28 15:08:03.261466 - 0.015214 - Executing: proc1 hi
# Description of argument(s):
- # include_args Indicates whether proc args should be
- # included in the result.
+ # include_args Indicates whether proc args should be included in the result.
set stack_ix_adjust [calc_wrap_stack_ix_adjust]
set level [expr -(2 + $stack_ix_adjust)]
@@ -733,12 +674,9 @@
# #(CDT) 2016/08/25 17:57:36 - Issuing: ls
# Description of arg(s):
- # cmd_buf The command to be executed by caller. If
- # this is blank, this procedure will search
- # up the stack for the first cmd_buf value
- # to use.
- # test_mode With test_mode set, your output will look
- # like this:
+ # cmd_buf The command to be executed by caller. If this is blank, this procedure
+ # will search up the stack for the first cmd_buf value to use.
+ # test_mode With test_mode set, your output will look like this:
# #(CDT) 2016/08/25 17:57:36 - (test_mode) Issuing: ls
@@ -759,8 +697,8 @@
proc sprint_call_stack { { indent 0 } } {
- # Return a call stack report for the given point in the program with line
- # numbers, procedure names and procedure parameters and arguments.
+ # Return a call stack report for the given point in the program with line numbers, procedure names and
+ # procedure parameters and arguments.
# Sample output:
@@ -774,8 +712,7 @@
# ---------------------------------------------------------------------------
# Description of arguments:
- # indent The number of characters to indent each
- # line of output.
+ # indent The number of characters to indent each line of output.
append buffer "[sprint_dashes ${indent}]"
append buffer "[string repeat " " $indent]TCL procedure call stack\n\n"
@@ -810,15 +747,13 @@
proc sprint_error_report { { error_text "\n" } { indent 0 } } {
- # Return a string with a standardized report which includes the caller's
- # error text, the call stack and the program header.
+ # Return a string with a standardized report which includes the caller's error text, the call stack and
+ # the program header.
# Description of arg(s):
- # error_text The error text to be included in the
- # report. The caller should include any
- # needed linefeeds.
- # indent The number of characters to indent each
- # line of output.
+ # error_text The error text to be included in the report. The caller should include
+ # any needed linefeeds.
+ # indent The number of characters to indent each line of output.
set width 120
set char "="
@@ -837,15 +772,13 @@
proc sprint_pgm_header { {indent 0} {linefeed 1} } {
- # Return a standardized header that programs should print at the beginning
- # of the run. It includes useful information like command line, pid,
- # userid, program parameters, etc.
+ # Return a standardized header that programs should print at the beginning of the run. It includes useful
+ # information like command line, pid, userid, program parameters, etc.
# Description of arguments:
- # indent The number of characters to indent each
- # line of output.
- # linefeed Indicates whether a line feed be included
- # at the beginning and end of the report.
+ # indent The number of characters to indent each line of output.
+ # linefeed Indicates whether a line feed be included at the beginning and end of the
+ # report.
global program_name
global pgm_name_var_name
@@ -898,8 +831,8 @@
proc sprint_pgm_footer {} {
- # Return a standardized footer that programs should print at the end of the
- # program run. It includes useful information like total run time, etc.
+ # Return a standardized footer that programs should print at the end of the program run. It includes
+ # useful information like total run time, etc.
global program_name
global pgm_name_var_name
@@ -933,12 +866,11 @@
# Example:
#
- # set desc "When in the Course of human events, it becomes necessary for
- # one people to dissolve the political bands which have connected them with
- # another, and to assume among the powers of the earth, the separate and
- # equal station to which the Laws of Nature and of Nature's God entitle
- # them, a decent respect to the opinions of mankind requires that they
- # should declare the causes which impel them to the separation."
+ # set desc "When in the Course of human events, it becomes necessary for one people to dissolve the
+ # political bands which have connected them with another, and to assume among the powers of the earth, the
+ # separate and equal station to which the Laws of Nature and of Nature's God entitle them, a decent respect
+ # to the opinions of mankind requires that they should declare the causes which impel them to the
+ # separation."
# set buffer [sprint_arg_desc "--declaration" $desc]
# puts $buffer
@@ -955,12 +887,10 @@
# which impel them to the separation.
# Description of argument(s):
- # arg_title The content that you want to appear on the
- # first line in column 1.
+ # arg_title The content that you want to appear on the first line in column 1.
# arg_desc The text that describes the argument.
# indent The number of characters to indent.
- # col1_width The width of column 1, which is the column
- # containing the arg_title.
+ # col1_width The width of column 1, which is the column containing the arg_title.
# line_width The total max width of each line of output.
set fold_width [expr $line_width - $col1_width]
@@ -1004,11 +934,9 @@
# First, create templates.
# Notes:
# - The resulting procedures will replace all registered passwords.
-# - The resulting "quiet" and "debug" print procedures will search the stack
-# for quiet and debug, respectively. That means that the if a procedure
-# calls qprint_var and the procedure has a local version of quiet set to 1,
-# the print will not occur, even if there is a global version of quiet set
-# to 0.
+# - The resulting "quiet" and "debug" print procedures will search the stack for quiet and debug,
+# respectively. That means that the if a procedure calls qprint_var and the procedure has a local version
+# of quiet set to 1, the print will not occur, even if there is a global version of quiet set to 0.
set print_proc_template " puts -nonewline<output_stream> \[replace_passwords"
append print_proc_template " \[<base_proc_name> {*}\$args\]\]\n}\n"
set qprint_proc_template " set quiet \[get_stack_var quiet 0\]\n if {"
@@ -1022,30 +950,22 @@
set print_proc_templates(d) $dprint_proc_template
proc create_print_wrapper_procs {proc_names {stderr_proc_names {}} } {
- # Generate code for print wrapper procs and return the generated code as a
- # string.
+ # Generate code for print wrapper procs and return the generated code as a string.
- # To illustrate, suppose there is a "print_foo_bar" proc in the proc_names
- # list.
+ # To illustrate, suppose there is a "print_foo_bar" proc in the proc_names list.
# This proc will...
# - Expect that there is an sprint_foo_bar proc already in existence.
- # - Create a print_foo_bar proc which calls sprint_foo_bar and prints the
- # result.
- # - Create a qprint_foo_bar proc which calls upon sprint_foo_bar only if
- # global value quiet is 0.
- # - Create a dprint_foo_bar proc which calls upon sprint_foo_bar only if
- # global value debug is 1.
+ # - Create a print_foo_bar proc which calls sprint_foo_bar and prints the result.
+ # - Create a qprint_foo_bar proc which calls upon sprint_foo_bar only if global value quiet is 0.
+ # - Create a dprint_foo_bar proc which calls upon sprint_foo_bar only if global value debug is 1.
- # Also, code will be generated to define aliases for each proc as well.
- # Each alias will be created by replacing "print_" in the proc name with "p"
- # For example, the alias for print_foo_bar will be pfoo_bar.
+ # Also, code will be generated to define aliases for each proc as well. Each alias will be created by
+ # replacing "print_" in the proc name with "p" For example, the alias for print_foo_bar will be pfoo_bar.
# Description of argument(s):
- # proc_names A list of procs for which print wrapper
- # proc code is to be generated.
- # stderr_proc_names A list of procs whose generated code
- # should print to stderr rather than to
- # stdout.
+ # proc_names A list of procs for which print wrapper proc code is to be generated.
+ # stderr_proc_names A list of procs whose generated code should print to stderr rather than
+ # to stdout.
global print_proc_template
global print_proc_templates
diff --git a/lib/redfish_plus.py b/lib/redfish_plus.py
index 9f4ade0..2257fc0 100755
--- a/lib/redfish_plus.py
+++ b/lib/redfish_plus.py
@@ -15,14 +15,11 @@
Description of argument(s):
status An HTTP status code (e.g. 200, 400, etc.).
- valid_status_codes A list of status codes that the caller
- considers acceptable. If this is a null
- list, then any status code is considered
- acceptable. Note that for the convenience
- of the caller, valid_status_codes may be
- either a python list or a string which can
- be evaluated to become a python list (e.g.
- "[200]").
+ valid_status_codes A list of status codes that the caller considers acceptable. If this is
+ a null list, then any status code is considered acceptable. Note that
+ for the convenience of the caller, valid_status_codes may be either a
+ python list or a string which can be evaluated to become a python list
+ (e.g. "[200]").
"""
if type(valid_status_codes) is not list:
@@ -39,13 +36,13 @@
class redfish_plus(HttpClient):
r"""
- redfish_plus is a wrapper for redfish rest that provides the following
- benefits vs. using redfish directly:
+ redfish_plus is a wrapper for redfish rest that provides the following benefits vs. using redfish
+ directly:
For rest_request functions (e.g. get, put, post, etc.):
- Function-call logging to stdout.
- - Automatic valid_status_codes processing (i.e. an exception will be
- raised if the rest response status code is not as expected.
+ - Automatic valid_status_codes processing (i.e. an exception will be raised if the rest response
+ status code is not as expected.
- Easily used from robot programs.
"""
@@ -56,11 +53,11 @@
Perform redfish rest request and return response.
This function provides the following additional functionality.
- - The calling function's call line is logged to standard out (provided
- that global variable "quiet" is not set).
+ - The calling function's call line is logged to standard out (provided that global variable "quiet"
+ is not set).
- The caller may include a valid_status_codes argument.
- - Callers may include inline python code strings to define arguments.
- This predominantly benefits robot callers.
+ - Callers may include inline python code strings to define arguments. This predominantly benefits
+ robot callers.
For example, instead of calling like this:
${data}= Create Dictionary HostName=${hostname}
@@ -72,50 +69,38 @@
... body=[('HostName', '${hostname}')]
Description of argument(s):
- func A reference to the parent class function
- which is to be called (e.g. get, put,
- etc.).
- args This is passed directly to the function
- referenced by the func argument (see the
- documentation for the corresponding
- redfish HttpClient method for details).
- kwargs This is passed directly to the function
- referenced by the func argument (see the
- documentation for the corresponding
- redfish HttpClient method for details)
- with the following exception: If kwargs
- contains a valid_status_codes key, it will
- be removed from kwargs and processed by
- this function. This allows the caller to
- indicate what rest status codes are
- acceptable. The default value is [200].
- See the valid_http_status_code function
- above for details.
+ func A reference to the parent class function which is to be called (e.g. get,
+ put, etc.).
+ args This is passed directly to the function referenced by the func argument
+ (see the documentation for the corresponding redfish HttpClient method
+ for details).
+ kwargs This is passed directly to the function referenced by the func argument
+ (see the documentation for the corresponding redfish HttpClient method
+ for details) with the following exception: If kwargs contains a
+ valid_status_codes key, it will be removed from kwargs and processed by
+ this function. This allows the caller to indicate what rest status codes
+ are acceptable. The default value is [200]. See the
+ valid_http_status_code function above for details.
Example uses:
From a python program:
- response =
- bmc_redfish.get("/redfish/v1/Managers/bmc/EthernetInterfaces", [200,
- 201])
+ response = bmc_redfish.get("/redfish/v1/Managers/bmc/EthernetInterfaces", [200, 201])
- If this call to the get method generates a response.status equal to
- anything other than 200 or 201, an exception will be raised.
+ If this call to the get method generates a response.status equal to anything other than 200 or 201,
+ an exception will be raised.
From a robot program:
BMC_Redfish.logout
- ${response}= BMC_Redfish.Get
- /redfish/v1/Managers/bmc/EthernetInterfaces valid_status_codes=[401]
+ ${response}= BMC_Redfish.Get /redfish/v1/Managers/bmc/EthernetInterfaces valid_status_codes=[401]
- As part of a robot test, the programmer has logged out to verify that
- the get request will generate a status code of 401 (i.e.
- "Unauthorized").
+ As part of a robot test, the programmer has logged out to verify that the get request will generate a
+ status code of 401 (i.e. "Unauthorized").
"""
gp.qprint_executing(stack_frame_ix=3, style=gp.func_line_style_short)
- # Convert python string object definitions to objects (mostly useful
- # for robot callers).
+ # Convert python string object definitions to objects (mostly useful for robot callers).
args = fa.args_to_objects(args)
kwargs = fa.args_to_objects(kwargs)
valid_status_codes = kwargs.pop('valid_status_codes', [200])
diff --git a/lib/source.tcl b/lib/source.tcl
index e01684e..d4a2978 100755
--- a/lib/source.tcl
+++ b/lib/source.tcl
@@ -1,12 +1,9 @@
-# This file is an aid in sourcing other tcl files. It provides the following
-# advantages:
-# - It shortens the number of lines of code needed to intelligently source
-# files.
-# - Its my_source procedure provides several benefits (see my_source prolog
-# below).
+# This file is an aid in sourcing other tcl files. It provides the following advantages:
+# - It shortens the number of lines of code needed to intelligently source files.
+# - Its my_source procedure provides several benefits (see my_source prolog below).
-# By convention, this file, or a link to this file, must exist in one of the
-# directories named in the PATH environment variable.
+# By convention, this file, or a link to this file, must exist in one of the directories named in the PATH
+# environment variable.
# Example use:
# source [exec bash -c "which source.tcl"]
@@ -17,8 +14,8 @@
proc tcl_which { file_name } {
- # Search the PATH environment variable for the first executable instance of
- # $file_name and return the full path. On failure, return a blank string.
+ # Search the PATH environment variable for the first executable instance of $file_name and return the full
+ # path. On failure, return a blank string.
# This procedure runs much faster than [exec bash -c "which $file_name"].
@@ -45,8 +42,7 @@
# Source each file in the source_files list.
- # This procedure provides the following benefits verses just using the
- # source command directly.
+ # This procedure provides the following benefits verses just using the source command directly.
# - Use of PATH environment variable to locate files.
# - Better error handling.
# - Will only source each file once.
diff --git a/lib/tally_sheet.py b/lib/tally_sheet.py
index 322fac6..c48e161 100755
--- a/lib/tally_sheet.py
+++ b/lib/tally_sheet.py
@@ -20,8 +20,8 @@
class tally_sheet:
r"""
- This class is the implementation of a tally sheet. The sheet can be
- viewed as rows and columns. Each row has a unique key field.
+ This class is the implementation of a tally sheet. The sheet can be viewed as rows and columns. Each
+ row has a unique key field.
This class provides methods to tally the results (totals, etc.).
@@ -29,17 +29,14 @@
# Create an ordered dict to represent your field names/initial values.
try:
- boot_results_fields = collections.OrderedDict([('total', 0), ('pass',
- 0), ('fail', 0)])
+ boot_results_fields = collections.OrderedDict([('total', 0), ('pass', 0), ('fail', 0)])
except AttributeError:
boot_results_fields = DotDict([('total', 0), ('pass', 0), ('fail', 0)])
# Create the tally sheet.
- boot_test_results = tally_sheet('boot type', boot_results_fields,
- 'boot_test_results')
+ boot_test_results = tally_sheet('boot type', boot_results_fields, 'boot_test_results')
# Set your sum fields (fields which are to be totalled).
boot_test_results.set_sum_fields(['total', 'pass', 'fail'])
- # Set calc fields (within a row, a certain field can be derived from
- # other fields in the row.
+ # Set calc fields (within a row, a certain field can be derived from other fields in the row.
boot_test_results.set_calc_fields(['total=pass+fail'])
# Create some records.
@@ -62,7 +59,7 @@
BMC Power On 2 1 1
BMC Power Off 1 1 0
===================================================
- Totals 3 2 1
+ Totals 3 2 1
"""
@@ -74,10 +71,8 @@
Create a tally sheet object.
Description of arguments:
- row_key_field_name The name of the row key field (e.g.
- boot_type, team_name, etc.)
- init_fields_dict A dictionary which contains field
- names/initial values.
+ row_key_field_name The name of the row key field (e.g. boot_type, team_name, etc.)
+ init_fields_dict A dictionary which contains field names/initial values.
obj_name The name of the tally sheet.
"""
@@ -85,9 +80,8 @@
# The row key field uniquely identifies the row.
self.__row_key_field_name = row_key_field_name
# Create a "table" which is an ordered dictionary.
- # If we're running python 2.7 or later, collections has an
- # OrderedDict we can use. Otherwise, we'll try to use the DotDict (a
- # robot library). If neither of those are available, we fail.
+ # If we're running python 2.7 or later, collections has an OrderedDict we can use. Otherwise, we'll
+ # try to use the DotDict (a robot library). If neither of those are available, we fail.
try:
self.__table = collections.OrderedDict()
except AttributeError:
@@ -108,8 +102,8 @@
def set_sum_fields(self, sum_fields):
r"""
- Set the sum fields, i.e. create a list of field names which are to be
- summed and included on the totals line of reports.
+ Set the sum fields, i.e. create a list of field names which are to be summed and included on the
+ totals line of reports.
Description of arguments:
sum_fields A list of field names.
@@ -119,14 +113,12 @@
def set_calc_fields(self, calc_fields):
r"""
- Set the calc fields, i.e. create a list of field names within a given
- row which are to be calculated for the user.
+ Set the calc fields, i.e. create a list of field names within a given row which are to be calculated
+ for the user.
Description of arguments:
- calc_fields A string expression such as
- 'total=pass+fail' which shows which field
- on a given row is derived from other
- fields in the same row.
+ calc_fields A string expression such as 'total=pass+fail' which shows which field on
+ a given row is derived from other fields in the same row.
"""
self.__calc_fields = calc_fields
@@ -137,13 +129,10 @@
Description of arguments:
row_key A unique key value.
- init_fields_dict A dictionary of field names/initial
- values. The number of fields in this
- dictionary must be the same as what was
- specified when the tally sheet was
- created. If no value is passed, the value
- used to create the tally sheet will be
- used.
+ init_fields_dict A dictionary of field names/initial values. The number of fields in this
+ dictionary must be the same as what was specified when the tally sheet
+ was created. If no value is passed, the value used to create the tally
+ sheet will be used.
"""
if row_key in self.__table:
@@ -163,48 +152,40 @@
Update a field in a row with the specified value.
Description of arguments:
- row_key A unique key value that identifies the row
- to be updated.
- field_key The key that identifies which field in the
- row that is to be updated.
- value The value to set into the specified
- row/field.
+ row_key A unique key value that identifies the row to be updated.
+ field_key The key that identifies which field in the row that is to be updated.
+ value The value to set into the specified row/field.
"""
self.__table[row_key][field_key] = value
def inc_row_field(self, row_key, field_key):
r"""
- Increment the value of the specified field in the specified row. The
- value of the field must be numeric.
+ Increment the value of the specified field in the specified row. The value of the field must be
+ numeric.
Description of arguments:
- row_key A unique key value that identifies the row
- to be updated.
- field_key The key that identifies which field in the
- row that is to be updated.
+ row_key A unique key value that identifies the row to be updated.
+ field_key The key that identifies which field in the row that is to be updated.
"""
self.__table[row_key][field_key] += 1
def dec_row_field(self, row_key, field_key):
r"""
- Decrement the value of the specified field in the specified row. The
- value of the field must be numeric.
+ Decrement the value of the specified field in the specified row. The value of the field must be
+ numeric.
Description of arguments:
- row_key A unique key value that identifies the row
- to be updated.
- field_key The key that identifies which field in the
- row that is to be updated.
+ row_key A unique key value that identifies the row to be updated.
+ field_key The key that identifies which field in the row that is to be updated.
"""
self.__table[row_key][field_key] -= 1
def calc(self):
r"""
- Calculate totals and row calc fields. Also, return totals_line
- dictionary.
+ Calculate totals and row calc fields. Also, return totals_line dictionary.
"""
self.__totals_line = copy.deepcopy(self.__init_fields_dict)
@@ -233,8 +214,7 @@
def sprint_obj(self):
r"""
- sprint the fields of this object. This would normally be for debug
- purposes.
+ sprint the fields of this object. This would normally be for debug purposes.
"""
buffer = ""
@@ -253,8 +233,7 @@
def print_obj(self):
r"""
- print the fields of this object to stdout. This would normally be for
- debug purposes.
+ print the fields of this object to stdout. This would normally be for debug purposes.
"""
sys.stdout.write(self.sprint_obj())
diff --git a/lib/tools.exp b/lib/tools.exp
index f8e876d..0fb474f 100755
--- a/lib/tools.exp
+++ b/lib/tools.exp
@@ -1,7 +1,6 @@
#!/usr/bin/expect
-# This file provides many valuable expect procedures like handle_timeout and
-# handle_eof.
+# This file provides many valuable expect procedures like handle_timeout and handle_eof.
my_source [list print.tcl]
@@ -11,8 +10,7 @@
# Print timeout error message to stderr and exit 1.
# Description of argument(s):
- # description A description of what was being expected
- # (e.g. "an SOL login prompt").
+ # description A description of what was being expected (e.g. "an SOL login prompt").
global spawn_id
global expect_out
@@ -45,8 +43,7 @@
# Print end-of-file error message to stderr and exit 1.
# Description of argument(s):
- # description A description of what was being expected
- # (e.g. "an SOL login prompt").
+ # description A description of what was being expected (e.g. "an SOL login prompt").
global spawn_id
@@ -67,36 +64,26 @@
proc expect_wrap {pattern_list message {timeout 15} {fail_on_timeout 1}} {
- # Run the expect command for the caller and return the list index of the
- # matching pattern.
+ # Run the expect command for the caller and return the list index of the matching pattern.
- # This function offers the following benefits over calling the expect
- # command directly:
- # - It makes program debug easier. When the program is run with --debug=1,
- # this function prints useful debug output.
+ # This function offers the following benefits over calling the expect command directly:
+ # - It makes program debug easier. When the program is run with --debug=1, this function prints useful
+ # debug output.
# - It will do standardized timeout and eof handling.
# Description of argument(s):
- # pattern_list A list of patterns to be matched. If one
- # of the patterns matches, the list index of
- # the matching item will be returned. By
- # default, each pattern is presumed to be a
- # regex. If the caller wishes to, they may
- # precede each pattern with either of the
- # following: "-re ", "-gl " or "-ex " in
- # order to explicitly choose the kind of
- # match to be done..
- # message A message explaining what is being
- # expected (e.g. "an SOL login prompt").
+ # pattern_list A list of patterns to be matched. If one of the patterns matches, the
+ # list index of the matching item will be returned. By default, each
+ # pattern is presumed to be a regex. If the caller wishes to, they may
+ # precede each pattern with either of the following: "-re ", "-gl " or "-ex
+ # " in order to explicitly choose the kind of match to be done..
+ # message A message explaining what is being expected (e.g. "an SOL login prompt").
# This will be included in output messages.
# timeout The expect timeout value.
- # fail_on_timeout A flag governing the behavior when the
- # expect command results in a timeout. If
- # set to 1, this procedure will print an
- # error message to standard error and exit
- # the program with a non-zero return code.
- # If set to 0, it will return
- # [expect_wrap_timeout].
+ # fail_on_timeout A flag governing the behavior when the expect command results in a
+ # timeout. If set to 1, this procedure will print an error message to
+ # standard error and exit the program with a non-zero return code. If set
+ # to 0, it will return [expect_wrap_timeout].
# Example usage:
# set result [expect_wrap\
@@ -128,8 +115,8 @@
append cmd_buf "expect {\n"
set ix 0
foreach pattern $pattern_list {
- # Check to see whether the caller has specified a flag (e.g. "-re",
- # "-ex", etc.) at the beginning of the pattern.
+ # Check to see whether the caller has specified a flag (e.g. "-re", "-ex", etc.) at the beginning of the
+ # pattern.
set tokens [split $pattern " "]
if { [lsearch $flags [lindex $tokens 0]] != -1 } {
# Caller specified a flag.
@@ -174,14 +161,12 @@
# Send the buffer to the spawned process.
- # This function offers the following benefits over calling the send command
- # directly:
- # - It makes program debug easier. When the program is run with --debug=1,
- # this function prints useful debug output.
+ # This function offers the following benefits over calling the send command directly:
+ # - It makes program debug easier. When the program is run with --debug=1, this function prints useful
+ # debug output.
# Description of argument(s):
- # buffer The string to be sent to the spawned
- # process.
+ # buffer The string to be sent to the spawned process.
# add_lf Send a line feed after sending the buffer.
# Example usage.
@@ -212,42 +197,30 @@
proc shell_command {command_string {prompt_regex} { quiet {} } \
{ test_mode {} } { show_err {} } { ignore_err {} } {trim_cr_lf 1}} {
- # Execute the command_string on the shell command line and return a list
- # consisting of 1) the return code of the command 2) the stdout/stderr.
+ # Execute the command_string on the shell command line and return a list consisting of 1) the return code
+ # of the command 2) the stdout/stderr.
- # It is the caller's responsibility to spawn the appropriate process
- # (ssh,telnet) and to get the process to a shell command line (by logging
- # in, etc.).
+ # It is the caller's responsibility to spawn the appropriate process (ssh,telnet) and to get the process
+ # to a shell command line (by logging in, etc.).
# Description of argument(s):
- # command_string The command string which is to be run on
- # the shell (e.g. "hostname" or "grep this
- # that").
- # prompt_regex A regular expression to match the prompt
- # for current shell to run on (e.g "/ #").
- # quiet Indicates whether this procedure should
- # run the print_issuing() procedure which
- # prints "Issuing: <cmd string>" to stdout.
- # The default value is 0.
- # test_mode If test_mode is set, this procedure will
- # not actually run the command. If
- # print_output is set, it will print
- # "(test_mode) Issuing: <cmd string>" to
- # stdout. The default value is 0.
- # show_err If show_err is set, this procedure will
- # print a standardized error report if the
- # shell command returns non-zero. The
- # default value is 1.
- # ignore_err If ignore_err is set, this procedure will
- # not fail if the shell command fails.
- # However, if ignore_err is not set, this
- # procedure will exit 1 if the shell command
- # fails. The default value is 1.
- # trim_cr_lf Trim any trailing carriage return or line
- # feed from the result.
+ # command_string The command string which is to be run on the shell (e.g. "hostname" or
+ # "grep this that").
+ # prompt_regex A regular expression to match the prompt for current shell to run on (e.g
+ # "/ #").
+ # quiet Indicates whether this procedure should run the print_issuing() procedure
+ # which prints "Issuing: <cmd string>" to stdout. The default value is 0.
+ # test_mode If test_mode is set, this procedure will not actually run the command.
+ # If print_output is set, it will print "(test_mode) Issuing: <cmd string>"
+ # to stdout. The default value is 0.
+ # show_err If show_err is set, this procedure will print a standardized error report
+ # if the shell command returns non-zero. The default value is 1.
+ # ignore_err If ignore_err is set, this procedure will not fail if the shell command
+ # fails. However, if ignore_err is not set, this procedure will exit 1 if
+ # the shell command fails. The default value is 1.
+ # trim_cr_lf Trim any trailing carriage return or line feed from the result.
- # Set defaults (this section allows users to pass blank values for certain
- # args).
+ # Set defaults (this section allows users to pass blank values for certain args).
set_var_default quiet [get_stack_var quiet 0 2]
set_var_default test_mode 0
set_var_default show_err 1
diff --git a/lib/valid.tcl b/lib/valid.tcl
index 4d5bdb0..aea4b3d 100755
--- a/lib/valid.tcl
+++ b/lib/valid.tcl
@@ -1,39 +1,29 @@
#!/usr/bin/wish
-# This file provides many valuable validation procedures such as valid_value,
-# valid_integer, etc.
+# This file provides many valuable validation procedures such as valid_value, valid_integer, etc.
my_source [list print.tcl call_stack.tcl]
proc valid_value { var_name { invalid_values {}} { valid_values {}} } {
- # If the value of the variable named in var_name is not valid, print an
- # error message and exit the program with a non-zero return code.
+ # If the value of the variable named in var_name is not valid, print an error message and exit the program
+ # with a non-zero return code.
# Description of arguments:
- # var_name The name of the variable whose value is to
- # be validated.
- # invalid_values A list of invalid values. If the variable
- # value is equal to any value in the
- # invalid_values list, it is deemed to be
- # invalid. Note that if you specify
- # anything for invalid_values (below), the
- # valid_values list is not even processed.
- # In other words, specify either
- # invalid_values or valid_values but not
- # both. If no value is specified for either
- # invalid_values or valid_values,
- # invalid_values will default to a list with
- # one blank entry. This is useful if you
- # simply want to ensure that your variable
- # is non blank.
- # valid_values A list of invalid values. The variable
- # value must be equal to one of the values
- # in this list to be considered valid.
+ # var_name The name of the variable whose value is to be validated.
+ # invalid_values A list of invalid values. If the variable value is equal to any value in
+ # the invalid_values list, it is deemed to be invalid. Note that if you
+ # specify anything for invalid_values (below), the valid_values list is not
+ # even processed. In other words, specify either invalid_values or
+ # valid_values but not both. If no value is specified for either
+ # invalid_values or valid_values, invalid_values will default to a list
+ # with one blank entry. This is useful if you simply want to ensure that
+ # your variable is non blank.
+ # valid_values A list of invalid values. The variable value must be equal to one of the
+ # values in this list to be considered valid.
- # Call get_stack_var_level to relieve the caller of the need for declaring
- # the variable as global.
+ # Call get_stack_var_level to relieve the caller of the need for declaring the variable as global.
set stack_level [get_stack_var_level $var_name]
# Access the variable value.
upvar $stack_level $var_name var_value
@@ -97,16 +87,14 @@
proc valid_list { var_name args } {
- # If the value of the list variable named in var_name is not valid, print
- # an error message and exit the program with a non-zero return code.
+ # If the value of the list variable named in var_name is not valid, print an error message and exit the
+ # program with a non-zero return code.
# Description of arguments:
- # var_name The name of the variable whose value is to
- # be validated. This variable should be a
- # list. For each list alement, a call to
- # valid_value will be done.
- # args args will be passed directly to
- # valid_value. Please see valid_value for
+ # var_name The name of the variable whose value is to be validated. This variable
+ # should be a list. For each list alement, a call to valid_value will be
+ # done.
+ # args args will be passed directly to valid_value. Please see valid_value for
# details.
# Example call:
@@ -117,8 +105,8 @@
# In this example, this procedure will fail with the following message:
- ##(CDT) 2018/03/27 12:26:49.904870 - **ERROR** The following list has one
- # #or more invalid values (marked with "*"):
+ ##(CDT) 2018/03/27 12:26:49.904870 - **ERROR** The following list has one or more invalid values (marked
+ # #with "*"):
#
# proc_names:
# proc_names[0]: zero*
@@ -134,8 +122,7 @@
# valid_values[1]: two
# valid_values[2]: three
- # Call get_stack_var_level to relieve the caller of the need for declaring
- # the variable as global.
+ # Call get_stack_var_level to relieve the caller of the need for declaring the variable as global.
set stack_level [get_stack_var_level $var_name]
# Access the variable value.
upvar $stack_level $var_name var_value
@@ -153,20 +140,17 @@
# No errors found so return.
if { [llength $invalid_ix_list] == 0 } { return }
- # We want to do a print_list on the caller's list but we want to put an
- # asterisk by each invalid entry (see example in prolog).
+ # We want to do a print_list on the caller's list but we want to put an asterisk by each invalid entry
+ # (see example in prolog).
- # Make the caller's variable name, contained in $var_name, directly
- # accessible to this procedure.
+ # Make the caller's variable name, contained in $var_name, directly accessible to this procedure.
upvar $stack_level $var_name $var_name
# print_list the caller's list to a string.
set printed_var [sprint_list $var_name "" "" 1]
- # Now convert the caller's printed var string to a list for easy
- # manipulation.
+ # Now convert the caller's printed var string to a list for easy manipulation.
set printed_var_list [split $printed_var "\n"]
- # Loop through the erroneous index list and mark corresponding entries in
- # printed_var_list with asterisks.
+ # Loop through the erroneous index list and mark corresponding entries in printed_var_list with asterisks.
foreach ix $invalid_ix_list {
set new_value "[lindex $printed_var_list $ix]*"
set printed_var_list [lreplace $printed_var_list ${ix} ${ix} $new_value]
@@ -177,8 +161,8 @@
append error_message "The following list has one or more invalid values"
append error_message " (marked with \"*\"):\n\n"
append error_message $printed_var
- # Determine whether the caller passed invalid_values or valid_values in
- # order to create appropriate error message.
+ # Determine whether the caller passed invalid_values or valid_values in order to create appropriate error
+ # message.
if { [lindex $args 0] != "" } {
append error_message "\nIt must NOT be any of the following values:\n\n"
set invalid_values [lindex $args 0]
@@ -196,15 +180,13 @@
proc valid_integer { var_name } {
- # If the value of the variable named in var_name is not a valid integer,
- # print an error message and exit the program with a non-zero return code.
+ # If the value of the variable named in var_name is not a valid integer, print an error message and exit
+ # the program with a non-zero return code.
# Description of arguments:
- # var_name The name of the variable whose value is to
- # be validated.
+ # var_name The name of the variable whose value is to be validated.
- # Call get_stack_var_level to relieve the caller of the need for declaring
- # the variable as global.
+ # Call get_stack_var_level to relieve the caller of the need for declaring the variable as global.
set stack_level [get_stack_var_level $var_name]
# Access the variable value.
upvar $stack_level $var_name var_value
@@ -221,18 +203,15 @@
proc valid_dir_path { var_name { add_slash 1 } } {
- # If the value of the variable named in var_name is not a valid directory
- # path, print an error message and exit the program with a non-zero return
- # code.
+ # If the value of the variable named in var_name is not a valid directory path, print an error message and
+ # exit the program with a non-zero return code.
# Description of arguments:
- # var_name The name of the variable whose value is to
- # be validated.
- # add_slash If set to 1, this procedure will add a
- # trailing slash to the directory path value.
+ # var_name The name of the variable whose value is to be validated.
+ # add_slash If set to 1, this procedure will add a trailing slash to the directory
+ # path value.
- # Call get_stack_var_level to relieve the caller of the need for declaring
- # the variable as global.
+ # Call get_stack_var_level to relieve the caller of the need for declaring the variable as global.
set stack_level [get_stack_var_level $var_name]
# Access the variable value.
upvar $stack_level $var_name var_value
@@ -253,15 +232,13 @@
proc valid_file_path { var_name } {
- # If the value of the variable named in var_name is not a valid file path,
- # print an error message and exit the program with a non-zero return code.
+ # If the value of the variable named in var_name is not a valid file path, print an error message and exit
+ # the program with a non-zero return code.
# Description of arguments:
- # var_name The name of the variable whose value is to
- # be validated.
+ # var_name The name of the variable whose value is to be validated.
- # Call get_stack_var_level to relieve the caller of the need for declaring
- # the variable as global.
+ # Call get_stack_var_level to relieve the caller of the need for declaring the variable as global.
set stack_level [get_stack_var_level $var_name]
# Access the variable value.
upvar $stack_level $var_name var_value
@@ -282,8 +259,7 @@
# Prompt user for password and return result.
- # On error, print to stderr and terminate the program with non-zero return
- # code.
+ # On error, print to stderr and terminate the program with non-zero return code.
set prompt\
[string trimright [sprint_varx "Please enter $password_var_name" ""] "\n"]
@@ -320,17 +296,14 @@
proc valid_password { var_name { prompt_user 1 } } {
- # If the value of the variable named in var_name is not a valid password,
- # print an error message and exit the program with a non-zero return code.
+ # If the value of the variable named in var_name is not a valid password, print an error message and exit
+ # the program with a non-zero return code.
# Description of arguments:
- # var_name The name of the variable whose value is to
- # be validated.
- # prompt_user If the variable has a blank value, prompt
- # the user for a value.
+ # var_name The name of the variable whose value is to be validated.
+ # prompt_user If the variable has a blank value, prompt the user for a value.
- # Call get_stack_var_level to relieve the caller of the need for declaring
- # the variable as global.
+ # Call get_stack_var_level to relieve the caller of the need for declaring the variable as global.
set stack_level [get_stack_var_level $var_name]
# Access the variable value.
upvar $stack_level $var_name var_value
@@ -350,29 +323,24 @@
proc process_pw_file_path {pw_file_path_var_name} {
- # Process a password file path parameter by setting or validating the
- # corresponding password variable.
+ # Process a password file path parameter by setting or validating the corresponding password variable.
- # For example, let's say you have an os_pw_file_path parm defined. This
- # procedure will set the global os_password variable.
+ # For example, let's say you have an os_pw_file_path parm defined. This procedure will set the global
+ # os_password variable.
- # If there is no os_password program parm defined, then the pw_file_path
- # must exist and will be validated by this procedure. If there is an
- # os_password program parm defined, then either the os_pw_file_path must be
- # valid or the os_password must be valid. Again, this procedure will verify
- # all of this.
+ # If there is no os_password program parm defined, then the pw_file_path must exist and will be validated
+ # by this procedure. If there is an os_password program parm defined, then either the os_pw_file_path must
+ # be valid or the os_password must be valid. Again, this procedure will verify all of this.
- # When a valid pw_file_path exists, this program will read the password
- # from it and set the global password variable with the value.
- # Finally, this procedure will call valid_password which will prompt user
- # if password has not been obtained by this point.
+ # When a valid pw_file_path exists, this program will read the password from it and set the global
+ # password variable with the value.
+ # Finally, this procedure will call valid_password which will prompt user if password has not been
+ # obtained by this point.
# Description of argument(s):
- # pw_file_path_var_name The name of a global variable that
- # contains a file path which in turn
- # contains a password value. The variable
- # name must end in "pw_file_path" (e.g.
- # "os_pw_file_path").
+ # pw_file_path_var_name The name of a global variable that contains a file path which in turn
+ # contains a password value. The variable name must end in "pw_file_path"
+ # (e.g. "os_pw_file_path").
# Verify that $pw_file_path_var_name ends with "pw_file_path".
if { ! [regexp -expanded "pw_file_path$" $pw_file_path_var_name] } {
@@ -387,8 +355,8 @@
global $pw_file_path_var_name
expand_shell_string $pw_file_path_var_name
- # Get the prefix portion of pw_file_path_var_name which is obtained by
- # stripping "pw_file_path" from the end.
+ # Get the prefix portion of pw_file_path_var_name which is obtained by stripping "pw_file_path" from the
+ # end.
regsub -expanded {pw_file_path$} $pw_file_path_var_name {} var_prefix
# Create password_var_name.
@@ -398,8 +366,7 @@
global longoptions pos_parms
regsub -all ":" "${longoptions} ${pos_parms}" {} parm_names
if { [lsearch -exact parm_names $password_var_name] == -1 } {
- # If no corresponding password program parm has been defined, then the
- # pw_file_path must be valid.
+ # If no corresponding password program parm has been defined, then the pw_file_path must be valid.
valid_file_path $pw_file_path_var_name
}
diff --git a/lib/var_funcs.py b/lib/var_funcs.py
index 4cd211e..560506c 100644
--- a/lib/var_funcs.py
+++ b/lib/var_funcs.py
@@ -21,8 +21,8 @@
def create_var_dict(*args):
r"""
- Create a dictionary whose keys/values are the arg names/arg values passed
- to it and return it to the caller.
+ Create a dictionary whose keys/values are the arg names/arg values passed to it and return it to the
+ caller.
Note: The resulting dictionary will be ordered.
@@ -68,12 +68,11 @@
Join a dictionary's keys and values into a string and return the string.
Description of argument(s):
- dict The dictionary whose keys and values are
- to be joined.
- record_delim The delimiter to be used to separate
- dictionary pairs in the resulting string.
- key_val_delim The delimiter to be used to separate keys
- from values in the resulting string.
+ dict The dictionary whose keys and values are to be joined.
+ record_delim The delimiter to be used to separate dictionary pairs in the resulting
+ string.
+ key_val_delim The delimiter to be used to separate keys from values in the resulting
+ string.
Example use:
@@ -85,8 +84,7 @@
var_dict:
var_dict[first_name]: Steve
var_dict[last_name]: Smith
- str1:
- first_name.Steve:last_name.Smith
+ str1: first_name.Steve:last_name.Smith
"""
format_str = '%s' + key_val_delim + '%s'
@@ -103,14 +101,10 @@
This function is the complement to join_dict.
Description of argument(s):
- string The string to be split into a dictionary.
- The string must have the proper delimiters
- in it. A string created by join_dict
- would qualify.
- record_delim The delimiter to be used to separate
- dictionary pairs in the input string.
- key_val_delim The delimiter to be used to separate
- keys/values in the input string.
+ string The string to be split into a dictionary. The string must have the
+ proper delimiters in it. A string created by join_dict would qualify.
+ record_delim The delimiter to be used to separate dictionary pairs in the input string.
+ key_val_delim The delimiter to be used to separate keys/values in the input string.
Example use:
@@ -120,8 +114,7 @@
Program output.
- str1:
- first_name.Steve:last_name.Smith
+ str1: first_name.Steve:last_name.Smith
new_dict:
new_dict[first_name]: Steve
new_dict[last_name]: Smith
@@ -150,12 +143,10 @@
Create a file path using the given parameters and return it.
Description of argument(s):
- file_name_dict A dictionary with keys/values which are to
- appear as part of the file name.
- dir_path The dir_path that is to appear as part of
- the file name.
- file_suffix A suffix to be included as part of the
- file name.
+ file_name_dict A dictionary with keys/values which are to appear as part of the file
+ name.
+ dir_path The dir_path that is to appear as part of the file name.
+ file_suffix A suffix to be included as part of the file name.
"""
dir_path = gm.add_trailing_slash(dir_path)
@@ -164,8 +155,7 @@
def parse_file_path(file_path):
r"""
- Parse a file path created by create_file_path and return the result as a
- dictionary.
+ Parse a file path created by create_file_path and return the result as a dictionary.
This function is the complement to create_file_path.
@@ -180,8 +170,7 @@
Program output.
boot_results_file_path:
- /tmp/pgm_name.obmc_boot_test:openbmc_nickname.beye6:master_pid.2039:boot_re
- sults
+ /tmp/pgm_name.obmc_boot_test:openbmc_nickname.beye6:master_pid.2039:boot_results
file_path_data:
file_path_data[dir_path]: /tmp/
file_path_data[pgm_name]: obmc_boot_test
@@ -213,24 +202,22 @@
r"""
Parse a key/value string and return as a key/value tuple.
- This function is useful for parsing a line of program output or data that
- is in the following form:
+ This function is useful for parsing a line of program output or data that is in the following form:
<key or variable name><delimiter><value>
An example of a key/value string would be as follows:
Current Limit State: No Active Power Limit
- In the example shown, the delimiter is ":". The resulting key would be as
- follows:
+ In the example shown, the delimiter is ":". The resulting key would be as follows:
Current Limit State
- Note: If one were to take the default values of to_lower=1 and
- underscores=1, the resulting key would be as follows:
+ Note: If one were to take the default values of to_lower=1 and underscores=1, the resulting key would be
+ as follows:
current_limit_state
- The to_lower and underscores arguments are provided for those who wish to
- have their key names have the look and feel of python variable names.
+ The to_lower and underscores arguments are provided for those who wish to have their key names have the
+ look and feel of python variable names.
The resulting value for the example above would be as follows:
No Active Power Limit
@@ -238,19 +225,15 @@
Another example:
name=Mike
- In this case, the delim would be "=", the key is "name" and the value is
- "Mike".
+ In this case, the delim would be "=", the key is "name" and the value is "Mike".
Description of argument(s):
string The string to be parsed.
- delim The delimiter which separates the key from
- the value.
- strip The characters (if any) to strip from the
- beginning and end of both the key and the
- value.
+ delim The delimiter which separates the key from the value.
+ strip The characters (if any) to strip from the beginning and end of both the
+ key and the value.
to_lower Change the key name to lower case.
- underscores Change any blanks found in the key name to
- underscores.
+ underscores Change any blanks found in the key name to underscores.
"""
pair = string.split(delim)
@@ -273,8 +256,7 @@
process_indent=0,
**args):
r"""
- Convert a list containing key/value strings or tuples to a dictionary and
- return it.
+ Convert a list containing key/value strings or tuples to a dictionary and return it.
See docstring of parse_key_value function for details on key/value strings.
@@ -322,8 +304,7 @@
[content-length]: 559
[x-xss-protection]: 1; mode=block
- Another example containing a sub-list (see process_indent description
- below):
+ Another example containing a sub-list (see process_indent description below):
Provides Device SDRs : yes
Additional Device Support :
@@ -332,11 +313,9 @@
FRU Inventory Device
Chassis Device
- Note that the 2 qualifications for containing a sub-list are met: 1)
- 'Additional Device Support' has no value and 2) The entries below it are
- indented. In this case those entries contain no delimiters (":") so they
- will be processed as a list rather than as a dictionary. The result would
- be as follows:
+ Note that the 2 qualifications for containing a sub-list are met: 1) 'Additional Device Support' has no
+ value and 2) The entries below it are indented. In this case those entries contain no delimiters (":")
+ so they will be processed as a list rather than as a dictionary. The result would be as follows:
mc_info:
mc_info[provides_device_sdrs]: yes
@@ -347,20 +326,14 @@
mc_info[additional_device_support][3]: Chassis Device
Description of argument(s):
- list A list of key/value strings. (See
- docstring of parse_key_value function for
- details).
- process_indent This indicates that indented
- sub-dictionaries and sub-lists are to be
- processed as such. An entry may have a
- sub-dict or sub-list if 1) It has no value
- other than blank 2) There are entries
- below it that are indented. Note that
- process_indent is not allowed for a list
- of tuples (vs. a list of key/value
- strings).
- **args Arguments to be interpreted by
- parse_key_value. (See docstring of
+ list A list of key/value strings. (See docstring of parse_key_value function
+ for details).
+ process_indent This indicates that indented sub-dictionaries and sub-lists are to be
+ processed as such. An entry may have a sub-dict or sub-list if 1) It has
+ no value other than blank 2) There are entries below it that are
+ indented. Note that process_indent is not allowed for a list of tuples
+ (vs. a list of key/value strings).
+ **args Arguments to be interpreted by parse_key_value. (See docstring of
parse_key_value function for details).
"""
@@ -389,18 +362,15 @@
indent = len(entry) - len(entry.lstrip())
if indent > parent_indent and parent_value == "":
- # This line is indented compared to the parent entry and the
- # parent entry has no value.
+ # This line is indented compared to the parent entry and the parent entry has no value.
# Append the entry to sub_list for later processing.
sub_list.append(str(entry))
continue
- # Process any outstanding sub_list and add it to
- # result_dict[parent_key].
+ # Process any outstanding sub_list and add it to result_dict[parent_key].
if len(sub_list) > 0:
if any(delim in word for word in sub_list):
- # If delim is found anywhere in the sub_list, we'll process
- # as a sub-dictionary.
+ # If delim is found anywhere in the sub_list, we'll process as a sub-dictionary.
result_dict[parent_key] = key_value_list_to_dict(sub_list,
**args)
else:
@@ -416,8 +386,7 @@
# Any outstanding sub_list to be processed?
if len(sub_list) > 0:
if any(delim in word for word in sub_list):
- # If delim is found anywhere in the sub_list, we'll process as a
- # sub-dictionary.
+ # If delim is found anywhere in the sub_list, we'll process as a sub-dictionary.
result_dict[parent_key] = key_value_list_to_dict(sub_list, **args)
else:
result_dict[parent_key] = map(str.strip, sub_list)
@@ -428,8 +397,7 @@
def key_value_outbuf_to_dict(out_buf,
**args):
r"""
- Convert a buffer with a key/value string on each line to a dictionary and
- return it.
+ Convert a buffer with a key/value string on each line to a dictionary and return it.
Each line in the out_buf should end with a \n.
@@ -459,11 +427,9 @@
[sampling_period]: 0 seconds
Description of argument(s):
- out_buf A buffer with a key/value string on each
- line. (See docstring of parse_key_value
- function for details).
- **args Arguments to be interpreted by
- parse_key_value. (See docstring of
+ out_buf A buffer with a key/value string on each line. (See docstring of
+ parse_key_value function for details).
+ **args Arguments to be interpreted by parse_key_value. (See docstring of
parse_key_value function for details).
"""
@@ -475,11 +441,9 @@
def create_field_desc_regex(line):
r"""
- Create a field descriptor regular expression based on the input line and
- return it.
+ Create a field descriptor regular expression based on the input line and return it.
- This function is designed for use by the list_to_report function (defined
- below).
+ This function is designed for use by the list_to_report function (defined below).
Example:
@@ -491,8 +455,7 @@
(.{8}) (.{12}) (.{18}) (.{24})
- This means that other report lines interpreted using the regular
- expression are expected to have:
+ This means that other report lines interpreted using the regular expression are expected to have:
- An 8 character field
- 3 spaces
- A 12 character field
@@ -502,8 +465,8 @@
- A 24 character field
Description of argument(s):
- line A line consisting of dashes to represent
- fields and spaces to delimit fields.
+ line A line consisting of dashes to represent fields and spaces to delimit
+ fields.
"""
# Split the line into a descriptors list. Example:
@@ -541,16 +504,14 @@
to_lower=1,
field_delim=None):
r"""
- Convert a list containing report text lines to a report "object" and
- return it.
+ Convert a list containing report text lines to a report "object" and return it.
- The first entry in report_list must be a header line consisting of column
- names delimited by white space. No column name may contain white space.
- The remaining report_list entries should contain tabular data which
- corresponds to the column names.
+ The first entry in report_list must be a header line consisting of column names delimited by white space.
+ No column name may contain white space. The remaining report_list entries should contain tabular data
+ which corresponds to the column names.
- A report object is a list where each entry is a dictionary whose keys are
- the field names from the first entry in report_list.
+ A report object is a list where each entry is a dictionary whose keys are the field names from the first
+ entry in report_list.
Example:
Given the following report_list as input:
@@ -578,38 +539,31 @@
[use%]: 0%
[mounted]: /dev
- Notice that because "Mounted on" contains a space, "on" would be
- considered the 7th field. In this case, there is never any data in field
- 7 so things work out nicely. A caller could do some pre-processing if
+ Notice that because "Mounted on" contains a space, "on" would be considered the 7th field. In this case,
+ there is never any data in field 7 so things work out nicely. A caller could do some pre-processing if
desired (e.g. change "Mounted on" to "Mounted_on").
Example 2:
- If the 2nd line of report data is a series of dashes and spaces as in the
- following example, that line will serve to delineate columns.
+ If the 2nd line of report data is a series of dashes and spaces as in the following example, that line
+ will serve to delineate columns.
The 2nd line of data is like this:
- ID status size
- tool,clientid,userid
+ ID status size tool,clientid,userid
-------- ------------ ------------------ ------------------------
20000001 in progress 0x7D0 ,,
Description of argument(s):
- report_list A list where each entry is one line of
- output from a report. The first entry
- must be a header line which contains
- column names. Column names may not
- contain spaces.
- to_lower Change the resulting key names to lower
- case.
- field_delim Indicates that there are field delimiters
- in report_list entries (which should be
- removed).
+ report_list A list where each entry is one line of output from a report. The first
+ entry must be a header line which contains column names. Column names
+ may not contain spaces.
+ to_lower Change the resulting key names to lower case.
+ field_delim Indicates that there are field delimiters in report_list entries (which
+ should be removed).
"""
if len(report_list) <= 1:
- # If we don't have at least a descriptor line and one line of data,
- # return an empty array.
+ # If we don't have at least a descriptor line and one line of data, return an empty array.
return []
if field_delim is not None:
@@ -632,8 +586,7 @@
if field_desc_regex == "":
columns = header_line.split()
else:
- # Pad the line with spaces on the right to facilitate processing with
- # field_desc_regex.
+ # Pad the line with spaces on the right to facilitate processing with field_desc_regex.
header_line = pad_format_string % header_line
columns = list(map(str.strip,
re.findall(field_desc_regex, header_line)[0]))
@@ -643,8 +596,7 @@
if field_desc_regex == "":
line = report_line.split()
else:
- # Pad the line with spaces on the right to facilitate processing
- # with field_desc_regex.
+ # Pad the line with spaces on the right to facilitate processing with field_desc_regex.
report_line = pad_format_string % report_line
line = list(map(str.strip,
re.findall(field_desc_regex, report_line)[0]))
@@ -660,8 +612,7 @@
def outbuf_to_report(out_buf,
**args):
r"""
- Convert a text buffer containing report lines to a report "object" and
- return it.
+ Convert a text buffer containing report lines to a report "object" and return it.
Refer to list_to_report (above) for more details.
@@ -669,8 +620,7 @@
Given the following out_buf:
- Filesystem 1K-blocks Used Available Use% Mounted
- on
+ Filesystem 1K-blocks Used Available Use% Mounted on
dev 247120 0 247120 0% /dev
tmpfs 248408 79792 168616 32% /run
@@ -694,15 +644,12 @@
Other possible uses:
- Process the output of a ps command.
- - Process the output of an ls command (the caller would need to supply
- column names)
+ - Process the output of an ls command (the caller would need to supply column names)
Description of argument(s):
- out_buf A text report. The first line must be a
- header line which contains column names.
- Column names may not contain spaces.
- **args Arguments to be interpreted by
- list_to_report. (See docstring of
+ out_buf A text report. The first line must be a header line which contains
+ column names. Column names may not contain spaces.
+ **args Arguments to be interpreted by list_to_report. (See docstring of
list_to_report function for details).
"""
@@ -712,8 +659,7 @@
def nested_get(key_name, structure):
r"""
- Return a list of all values from the nested structure that have the given
- key name.
+ Return a list of all values from the nested structure that have the given key name.
Example:
@@ -740,13 +686,10 @@
Description of argument(s):
key_name The key name (e.g. 'last_name').
- structure Any nested combination of lists or
- dictionaries (e.g. a dictionary, a
- dictionary of dictionaries, a list of
- dictionaries, etc.). This function will
- locate the given key at any level within
- the structure and include its value in the
- returned list.
+ structure Any nested combination of lists or dictionaries (e.g. a dictionary, a
+ dictionary of dictionaries, a list of dictionaries, etc.). This function
+ will locate the given key at any level within the structure and include
+ its value in the returned list.
"""
result = []
@@ -765,8 +708,7 @@
def match_struct(structure, match_dict, regex=False):
r"""
- Return True or False to indicate whether the structure matches the match
- dictionary.
+ Return True or False to indicate whether the structure matches the match dictionary.
Example:
@@ -789,23 +731,18 @@
match_struct(personnel, {'last_name': 'Johnson'}, regex=True)
Description of argument(s):
- structure Any nested combination of lists or
- dictionaries. See the prolog of
+ structure Any nested combination of lists or dictionaries. See the prolog of
get_nested() for details.
- match_dict Each key/value pair in match_dict must
- exist somewhere in the structure for the
- structure to be considered a match. A
- match value of None is considered a
- special case where the structure would be
- considered a match only if the key in
- question is found nowhere in the structure.
- regex Indicates whether the values in the
- match_dict should be interpreted as
+ match_dict Each key/value pair in match_dict must exist somewhere in the structure
+ for the structure to be considered a match. A match value of None is
+ considered a special case where the structure would be considered a match
+ only if the key in question is found nowhere in the structure.
+ regex Indicates whether the values in the match_dict should be interpreted as
regular expressions.
"""
- # The structure must match for each match_dict entry to be considered a
- # match. Therefore, any failure to match is grounds for returning False.
+ # The structure must match for each match_dict entry to be considered a match. Therefore, any failure
+ # to match is grounds for returning False.
for match_key, match_value in match_dict.items():
struct_key_values = nested_get(match_key, structure)
if match_value is None:
@@ -828,11 +765,10 @@
def filter_struct(structure, filter_dict, regex=False, invert=False):
r"""
- Filter the structure by removing any entries that do NOT contain the
- keys/values specified in filter_dict and return the result.
+ Filter the structure by removing any entries that do NOT contain the keys/values specified in filter_dict
+ and return the result.
- The selection process is directed only at the first-level entries of the
- structure.
+ The selection process is directed only at the first-level entries of the structure.
Example:
@@ -842,11 +778,9 @@
[/redfish/v1/Systems/system/Processors]:
[Members]:
[0]:
- [@odata.id]:
- /redfish/v1/Systems/system/Processors/cpu0
+ [@odata.id]: /redfish/v1/Systems/system/Processors/cpu0
[1]:
- [@odata.id]:
- /redfish/v1/Systems/system/Processors/cpu1
+ [@odata.id]: /redfish/v1/Systems/system/Processors/cpu1
[/redfish/v1/Systems/system/Processors/cpu0]:
[Status]:
[State]: Enabled
@@ -868,41 +802,31 @@
[State]: Enabled
[Health]: OK
- Note that the first item in the original properties directory had no key
- anywhere in the structure named "Health". Therefore, that item failed to
- make the cut. The next item did have a key named "Health" whose value was
- "OK" so it was included in the new structure. The third item had a key
- named "Health" but its value was not "OK" so it also failed to make the
- cut.
+ Note that the first item in the original properties directory had no key anywhere in the structure named
+ "Health". Therefore, that item failed to make the cut. The next item did have a key named "Health"
+ whose value was "OK" so it was included in the new structure. The third item had a key named "Health"
+ but its value was not "OK" so it also failed to make the cut.
Description of argument(s):
- structure Any nested combination of lists or
- dictionaries. See the prolog of
+ structure Any nested combination of lists or dictionaries. See the prolog of
get_nested() for details.
- filter_dict For each key/value pair in filter_dict,
- each entry in structure must contain the
- same key/value pair at some level. A
- filter_dict value of None is treated as a
- special case. Taking the example shown
- above, [('State', None)] would mean that
- the result should only contain records
+ filter_dict For each key/value pair in filter_dict, each entry in structure must
+ contain the same key/value pair at some level. A filter_dict value of
+ None is treated as a special case. Taking the example shown above,
+ [('State', None)] would mean that the result should only contain records
that have no State key at all.
- regex Indicates whether the values in the
- filter_dict should be interpreted as
+ regex Indicates whether the values in the filter_dict should be interpreted as
regular expressions.
- invert Invert the results. Instead of including
- only matching entries in the results,
- include only NON-matching entries in the
- results.
+ invert Invert the results. Instead of including only matching entries in the
+ results, include only NON-matching entries in the results.
"""
- # Convert filter_dict from a string containing a python object definition
- # to an actual python object (if warranted).
+ # Convert filter_dict from a string containing a python object definition to an actual python object (if
+ # warranted).
filter_dict = fa.source_to_object(filter_dict)
- # Determine whether structure is a list or a dictionary and process
- # accordingly. The result returned will be of the same type as the
- # structure.
+ # Determine whether structure is a list or a dictionary and process accordingly. The result returned
+ # will be of the same type as the structure.
if type(structure) is list:
result = []
for element in structure:
diff --git a/lib/var_stack.py b/lib/var_stack.py
index 2b2aa97..0b73b91 100644
--- a/lib/var_stack.py
+++ b/lib/var_stack.py
@@ -21,9 +21,9 @@
r"""
Define the variable stack class.
- An object of this class can be used to push variable name/variable value
- pairs which may be popped off the stack at a later time. The most obvious
- use for this is for saving variables that are to be restored later.
+ An object of this class can be used to push variable name/variable value pairs which may be popped off
+ the stack at a later time. The most obvious use for this is for saving variables that are to be restored
+ later.
Example code:
@@ -71,8 +71,7 @@
Initialize a new object of this class type.
Description of argument(s):
- obj_name The name of the object. This is useful
- for printing out the object.
+ obj_name The name of the object. This is useful for printing out the object.
"""
self.__obj_name = obj_name
@@ -84,8 +83,7 @@
def sprint_obj(self):
r"""
- sprint the fields of this object. This would normally be for debug
- purposes.
+ sprint the fields of this object. This would normally be for debug purposes.
"""
buffer = ""
@@ -98,8 +96,7 @@
def print_obj(self):
r"""
- print the fields of this object to stdout. This would normally be for
- debug purposes.
+ print the fields of this object to stdout. This would normally be for debug purposes.
"""
sys.stdout.write(self.sprint_obj())
@@ -112,18 +109,14 @@
Description of argument(s):
var_value The value being pushed.
- var_name The name of the variable containing the
- value to be pushed. This parameter is
- normally unnecessary as this function can
- figure out the var_name. This is provided
- for Robot callers. In this scenario, we
- are unable to get the variable name
- ourselves.
+ var_name The name of the variable containing the value to be pushed. This
+ parameter is normally unnecessary as this function can figure out the
+ var_name. This is provided for Robot callers. In this scenario, we are
+ unable to get the variable name ourselves.
"""
if var_name == "":
- # The caller has not passed a var_name so we will try to figure
- # it out.
+ # The caller has not passed a var_name so we will try to figure it out.
stack_frame_ix = 2
var_name = gp.get_arg_name(0, 1, stack_frame_ix)
if var_name in self.__stack_dict:
@@ -137,8 +130,7 @@
Pop the value for the given var_name from the stack and return it.
Description of argument(s):
- var_name The name of the variable whose value is to
- be popped.
+ var_name The name of the variable whose value is to be popped.
"""
return self.__stack_dict[var_name].pop()
diff --git a/lib/wrap_utils.py b/lib/wrap_utils.py
index b51844b..124d8c8 100755
--- a/lib/wrap_utils.py
+++ b/lib/wrap_utils.py
@@ -1,10 +1,9 @@
#!/usr/bin/env python
r"""
-This module provides functions which are useful for writing python wrapper
-functions (i.e. in this context, a wrapper function is one whose aim is to
-call some other function on the caller's behalf but to provide some additional
-functionality over and above what the base function provides).
+This module provides functions which are useful for writing python wrapper functions (i.e. in this context, a
+wrapper function is one whose aim is to call some other function on the caller's behalf but to provide some
+additional functionality over and above what the base function provides).
"""
import sys
@@ -18,12 +17,11 @@
This is a utility for helping to create wrapper functions.
- For example, if there existed a function with the following definition
- line:
+ For example, if there existed a function with the following definition line:
def sprint_foo_bar(headers=1):
- And the user wished to write a print_foo_bar wrapper function, they could
- call create_wrapper_def_and_call as follows:
+ And the user wished to write a print_foo_bar wrapper function, they could call
+ create_wrapper_def_and_call as follows:
func_def_line, call_line = create_wrapper_def_and_call("sprint_foo_bar",
"print_foo_bar")
@@ -32,23 +30,18 @@
func_def_line def print_foo_bar(headers=1):
call_line sprint_foo_bar(headers=headers)
- The func_def_line is suitable as the definition line for the wrapper
- function. The call_line is suitable for use in the new wrapper function
- wherever it wishes to call the base function. By explicitly specifying
- each parm in the definition and the call line, we allow the caller of the
- wrapper function to refer to any given parm by name rather than having to
- specify parms positionally.
+ The func_def_line is suitable as the definition line for the wrapper function. The call_line is suitable
+ for use in the new wrapper function wherever it wishes to call the base function. By explicitly
+ specifying each parm in the definition and the call line, we allow the caller of the wrapper function to
+ refer to any given parm by name rather than having to specify parms positionally.
Description of argument(s):
- base_func_name The name of the base function around which
- a wrapper is being created.
- wrap_func_name The name of the wrapper function being
- created.
+ base_func_name The name of the base function around which a wrapper is being created.
+ wrap_func_name The name of the wrapper function being created.
"""
- # Get caller's module name. Note: that for the present we've hard-coded
- # the stack_frame_ix value because we expect a call stack to this function
- # to be something like this:
+ # Get caller's module name. Note: that for the present we've hard-coded the stack_frame_ix value
+ # because we expect a call stack to this function to be something like this:
# caller
# create_print_wrapper_funcs
# create_func_def_string
@@ -82,8 +75,7 @@
num_defaults = len(base_default_list)
num_non_defaults = num_args - num_defaults
- # Create base_arg_default_string which is a reconstruction of the base
- # function's argument list.
+ # Create base_arg_default_string which is a reconstruction of the base function's argument list.
# Example base_arg_default_string:
# headers, last=2, first=[1]
# First, create a new list where each entry is of the form "arg=default".
@@ -119,34 +111,25 @@
func_body_template,
replace_dict):
r"""
- Create and return a complete function definition as a string. The caller
- may run "exec" on the resulting string to create the desired function.
+ Create and return a complete function definition as a string. The caller may run "exec" on the resulting
+ string to create the desired function.
Description of argument(s):
- base_func_name The name of the base function around which
- a wrapper is being created.
- wrap_func_name The name of the wrapper function being
- created.
- func_body_template A function body in the form of a list.
- Each list element represents one line of a
- function This is a template in so far as
- text substitutions will be done on it to
- arrive at a valid function definition.
- This template should NOT contain the
- function definition line (e.g. "def
- func1():"). create_func_def_string will
- pre-pend the definition line. The
- template should also contain the text
- "<call_line>" which is to be replaced by
- text which will call the base function
- with appropriate arguments.
- replace_dict A dictionary indicating additional text
- replacements to be done. For example, if
- the template contains a "<sub1>" (be sure
- to include the angle brackets), and the
- dictionary contains a key/value pair of
- 'sub1'/'replace1', then all instances of
- "<sub1>" will be replaced by "replace1".
+ base_func_name The name of the base function around which a wrapper is being created.
+ wrap_func_name The name of the wrapper function being created.
+ func_body_template A function body in the form of a list. Each list element represents one
+ line of a function This is a template in so far as text substitutions
+ will be done on it to arrive at a valid function definition. This
+ template should NOT contain the function definition line (e.g. "def
+ func1():"). create_func_def_string will pre-pend the definition line.
+ The template should also contain the text "<call_line>" which is to be
+ replaced by text which will call the base function with appropriate
+ arguments.
+ replace_dict A dictionary indicating additional text replacements to be done. For
+ example, if the template contains a "<sub1>" (be sure to include the
+ angle brackets), and the dictionary contains a key/value pair of
+ 'sub1'/'replace1', then all instances of "<sub1>" will be replaced by
+ "replace1".
"""
# Create the initial function definition list as a copy of the template.
@@ -154,11 +137,10 @@
# Call create_wrapper_def_and_call to get func_def_line and call_line.
func_def_line, call_line = create_wrapper_def_and_call(base_func_name,
wrap_func_name)
- # Insert the func_def_line composed by create_wrapper_def_and_call is the
- # first list entry.
+ # Insert the func_def_line composed by create_wrapper_def_and_call is the first list entry.
func_def.insert(0, func_def_line)
- # Make sure the replace_dict has a 'call_line'/call_line pair so that any
- # '<call_line>' text gets replaced as intended.
+ # Make sure the replace_dict has a 'call_line'/call_line pair so that any '<call_line>' text gets
+ # replaced as intended.
replace_dict['call_line'] = call_line
# Do the replacements.