From 78663629adf5e790e58ca0e908c7abd7aa96edb9 Mon Sep 17 00:00:00 2001 From: j-c-cook Date: Mon, 6 Jun 2022 10:49:31 -0500 Subject: [PATCH 01/13] Add passage of **options to the logger initialization --- can/logger.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/can/logger.py b/can/logger.py index 053001968..1c8b61c82 100644 --- a/can/logger.py +++ b/can/logger.py @@ -201,12 +201,15 @@ def main() -> None: print(f"Connected to {bus.__class__.__name__}: {bus.channel_info}") print(f"Can Logger (Started on {datetime.now()})") + options = {'append': True} + if results.file_size: logger = SizedRotatingLogger( - base_filename=results.log_file, max_bytes=results.file_size + base_filename=results.log_file, max_bytes=results.file_size, + **options ) else: - logger = Logger(filename=results.log_file) # type: ignore + logger = Logger(filename=results.log_file, **options) # type: ignore try: while True: From 7312246f77f520e6887d997e50ccb98fb3458ed2 Mon Sep 17 00:00:00 2001 From: j-c-cook Date: Mon, 6 Jun 2022 11:32:27 -0500 Subject: [PATCH 02/13] Add -a boolean option to the parser --- can/logger.py | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/can/logger.py b/can/logger.py index 1c8b61c82..853c69129 100644 --- a/can/logger.py +++ b/can/logger.py @@ -163,6 +163,15 @@ def main() -> None: default=None, ) + parser.add_argument( + '-a', + '--append', + dest='append_mode', + type=bool, + help='Whether to overwrite or append to an existing log file if it exists.', + default=False + ) + parser.add_argument( "-v", action="count", @@ -201,12 +210,10 @@ def main() -> None: print(f"Connected to {bus.__class__.__name__}: {bus.channel_info}") print(f"Can Logger (Started on {datetime.now()})") - options = {'append': True} - + options = {'append': results.append_mode} if results.file_size: logger = SizedRotatingLogger( - base_filename=results.log_file, max_bytes=results.file_size, - **options + base_filename=results.log_file, max_bytes=results.file_size, **options ) else: logger = Logger(filename=results.log_file, **options) # type: ignore From b2c3ee4b5b3409de6196540bf72d94ba9dbe2c01 Mon Sep 17 00:00:00 2001 From: j-c-cook Date: Mon, 6 Jun 2022 12:12:00 -0500 Subject: [PATCH 03/13] Add manual arg parse for boolean variables This solution is only required until Python>=3.9. --- can/logger.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/can/logger.py b/can/logger.py index 853c69129..f56a94c85 100644 --- a/can/logger.py +++ b/can/logger.py @@ -166,6 +166,7 @@ def main() -> None: parser.add_argument( '-a', '--append', + # action=argparse.BooleanOptionalAction, # Use when Python>=3.9 dest='append_mode', type=bool, help='Whether to overwrite or append to an existing log file if it exists.', @@ -210,6 +211,29 @@ def main() -> None: print(f"Connected to {bus.__class__.__name__}: {bus.channel_info}") print(f"Can Logger (Started on {datetime.now()})") + # argparser.py in Python 3.7.11 does not properly consider boolean arguments passed + # in from the command line. If a boolean is passed in, the variable must be converted + # to an integer 0 (False) or 1 (True). Once the project goes to a minimum of + # Python 3.9, the BooleanOptionalAction, this will no longer be required (Please do + # not use this as a reason to advocate a minimum Python version of 3.9). + boolean_args = ['-a', '--append'] + args = sys.argv[1:] + for i, bool_arg in enumerate(boolean_args): + for j, arg in enumerate(args): + if bool_arg == arg: + # Make sure the length of args is long enough to check the action + if len(args) >= j+1: + action = args[j+1] + else: + break + # Consider the action, and update the results to accurately embody request + if action == '0' or action == 'False': + results.append_mode = False + elif action == '1' or action == 'True': + results.append_mode = True + else: + pass + options = {'append': results.append_mode} if results.file_size: logger = SizedRotatingLogger( From 24aae13dbd8a16a9313eea8e09d18d161ddc41a8 Mon Sep 17 00:00:00 2001 From: j-c-cook Date: Mon, 6 Jun 2022 12:22:12 -0500 Subject: [PATCH 04/13] Fix the index-error check --- can/logger.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/can/logger.py b/can/logger.py index f56a94c85..a21b00220 100644 --- a/can/logger.py +++ b/can/logger.py @@ -221,8 +221,10 @@ def main() -> None: for i, bool_arg in enumerate(boolean_args): for j, arg in enumerate(args): if bool_arg == arg: - # Make sure the length of args is long enough to check the action - if len(args) >= j+1: + # Make sure the length of args is long enough to check the action, e.g. + # stop an index error from occurring. + # argparse.py should have already caught this, but this is a double check + if len(args)-1 >= j+1: action = args[j+1] else: break From 7a10157d600c590cc34843153d8e5079ac094125 Mon Sep 17 00:00:00 2001 From: j-c-cook Date: Mon, 6 Jun 2022 12:33:37 -0500 Subject: [PATCH 05/13] Bolster help documentation for new -a option --- can/logger.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/can/logger.py b/can/logger.py index a21b00220..94175d88e 100644 --- a/can/logger.py +++ b/can/logger.py @@ -169,7 +169,10 @@ def main() -> None: # action=argparse.BooleanOptionalAction, # Use when Python>=3.9 dest='append_mode', type=bool, - help='Whether to overwrite or append to an existing log file if it exists.', + help='A boolean option for ehether to overwrite or append to an existing log file ' + 'if it exists. To append to an existing log file, pass `True` or `1`. To ' + 'overwrite an existing log file, pass `False`, `0`, or do not add the -a ' + 'argument.', default=False ) From bad8a87eaf169d9ee0782a01cd1d9d97d0bac332 Mon Sep 17 00:00:00 2001 From: j-c-cook Date: Mon, 6 Jun 2022 13:37:18 -0500 Subject: [PATCH 06/13] Clean up variable names, notes, etc. --- can/logger.py | 29 +++++++++++++++-------------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/can/logger.py b/can/logger.py index 94175d88e..972e0802a 100644 --- a/can/logger.py +++ b/can/logger.py @@ -164,15 +164,15 @@ def main() -> None: ) parser.add_argument( - '-a', - '--append', - # action=argparse.BooleanOptionalAction, # Use when Python>=3.9 - dest='append_mode', + "-a", + "--append", + # "action"=argparse.BooleanOptionalAction, # Use when Python>=3.9 + dest="append_mode", type=bool, - help='A boolean option for ehether to overwrite or append to an existing log file ' - 'if it exists. To append to an existing log file, pass `True` or `1`. To ' - 'overwrite an existing log file, pass `False`, `0`, or do not add the -a ' - 'argument.', + help="A boolean option for whether to overwrite or append to an existing log " + "file if it exists. To append to an existing log file, pass `True` or `1`. " + "To overwrite an existing log file, pass `False`, `0`, or do not add the -a " + "argument. E.g. -a True or -a False.", default=False ) @@ -217,24 +217,25 @@ def main() -> None: # argparser.py in Python 3.7.11 does not properly consider boolean arguments passed # in from the command line. If a boolean is passed in, the variable must be converted # to an integer 0 (False) or 1 (True). Once the project goes to a minimum of - # Python 3.9, the BooleanOptionalAction, this will no longer be required (Please do - # not use this as a reason to advocate a minimum Python version of 3.9). + # Python 3.9, the BooleanOptionalAction can be used and the following code block will + # no longer be required (Please do not use this as a reason to advocate a minimum + # Python version of 3.9). boolean_args = ['-a', '--append'] args = sys.argv[1:] for i, bool_arg in enumerate(boolean_args): for j, arg in enumerate(args): if bool_arg == arg: - # Make sure the length of args is long enough to check the action, e.g. + # Make sure the length of args is long enough to check the toggle, e.g. # stop an index error from occurring. # argparse.py should have already caught this, but this is a double check if len(args)-1 >= j+1: - action = args[j+1] + toggle = args[j+1] else: break # Consider the action, and update the results to accurately embody request - if action == '0' or action == 'False': + if toggle == '0' or toggle == 'False': results.append_mode = False - elif action == '1' or action == 'True': + elif toggle == '1' or toggle == 'True': results.append_mode = True else: pass From 3446ee4a650e401fef94843b8827dd2e10892f2d Mon Sep 17 00:00:00 2001 From: j-c-cook Date: Tue, 7 Jun 2022 08:30:41 -0500 Subject: [PATCH 07/13] Whitespace formatting (PEP-8 style) --- can/logger.py | 83 +++++++++++++++++++++++++++++---------------------- 1 file changed, 47 insertions(+), 36 deletions(-) diff --git a/can/logger.py b/can/logger.py index 972e0802a..90370aa23 100644 --- a/can/logger.py +++ b/can/logger.py @@ -31,9 +31,10 @@ def _create_base_argument_parser(parser: argparse.ArgumentParser) -> None: parser.add_argument( "-c", "--channel", - help='''Most backend interfaces require some sort of channel. - For example with the serial interface the channel might be a rfcomm device: "/dev/rfcomm0" - With the socketcan interfaces valid channel examples include: "can0", "vcan0"''', + help=r'Most backend interfaces require some sort of channel. For ' + r'example with the serial interface the channel might be a rfcomm' + r' device: "/dev/rfcomm0". With the socketcan interface valid ' + r'channel examples include: "can0", "vcan0".', ) parser.add_argument( @@ -49,7 +50,8 @@ def _create_base_argument_parser(parser: argparse.ArgumentParser) -> None: "-b", "--bitrate", type=int, help="Bitrate to use for the CAN bus." ) - parser.add_argument("--fd", help="Activate CAN-FD support", action="store_true") + parser.add_argument( + "--fd", help="Activate CAN-FD support", action="store_true") parser.add_argument( "--data_bitrate", @@ -60,11 +62,10 @@ def _create_base_argument_parser(parser: argparse.ArgumentParser) -> None: parser.add_argument( "extra_args", nargs=argparse.REMAINDER, - help="""\ - The remaining arguments will be used for the interface initialisation. - For example, `-i vector -c 1 --app-name=MyCanApp` is the equivalent to - opening the bus with `Bus('vector', channel=1, app_name='MyCanApp')` - """, + help=r"The remaining arguments will be used for the interface " + r"initialisation. For example, `-i vector -c 1 --app-name=" + r"MyCanApp` is the equivalent to opening the bus with `Bus(" + r"'vector', channel=1, app_name='MyCanApp')", ) @@ -82,8 +83,10 @@ def _append_filter_argument( *args, "--filter", help="R|Space separated CAN filters for the given CAN interface:" - "\n : (matches when & mask == can_id & mask)" - "\n ~ (matches when & mask != can_id & mask)" + "\n : (matches when & mask ==" + " can_id & mask)" + "\n ~ (matches when & mask !=" + " can_id & mask)" "\nFx to show only frames with ID 0x100 to 0x103 and 0x200 to 0x20F:" "\n python -m can.viewer -f 100:7FC 200:7F0" "\nNote that the ID and mask are always interpreted as hex values", @@ -95,7 +98,8 @@ def _append_filter_argument( def _create_bus(parsed_args: Any, **kwargs: Any) -> can.Bus: - logging_level_names = ["critical", "error", "warning", "info", "debug", "subdebug"] + logging_level_names = \ + ["critical", "error", "warning", "info", "debug", "subdebug"] can.set_logging_level(logging_level_names[min(5, parsed_args.verbosity)]) config: Dict[str, Any] = {"single_handle": True, **kwargs} @@ -124,7 +128,8 @@ def _parse_filters(parsed_args: Any) -> CanFilters: elif "~" in filt: parts = filt.split("~") can_id = int(parts[0], base=16) | 0x20000000 # CAN_INV_FILTER - can_mask = int(parts[1], base=16) & 0x20000000 # socket.CAN_ERR_FLAG + can_mask = \ + int(parts[1], base=16) & 0x20000000 # socket.CAN_ERR_FLAG else: raise argparse.ArgumentError(None, "Invalid filter argument") can_filters.append({"can_id": can_id, "can_mask": can_mask}) @@ -134,14 +139,14 @@ def _parse_filters(parsed_args: Any) -> CanFilters: def _parse_additonal_config(unknown_args): return dict( - (arg.split("=", 1)[0].lstrip("--").replace("-", "_"), arg.split("=", 1)[1]) - for arg in unknown_args - ) + (arg.split("=", 1)[0].lstrip("--").replace("-", "_"), + arg.split("=", 1)[1]) for arg in unknown_args) def main() -> None: parser = argparse.ArgumentParser( - description="Log CAN traffic, printing messages to stdout or to a given file.", + description="Log CAN traffic, printing messages to stdout or to a " + "given file.", ) _create_base_argument_parser(parser) @@ -159,7 +164,8 @@ def main() -> None: "--file_size", dest="file_size", type=int, - help="Maximum file size in bytes. Rotate log file when size threshold is reached.", + help="Maximum file size in bytes. Rotate log file when size threshold " + "is reached.", default=None, ) @@ -169,10 +175,11 @@ def main() -> None: # "action"=argparse.BooleanOptionalAction, # Use when Python>=3.9 dest="append_mode", type=bool, - help="A boolean option for whether to overwrite or append to an existing log " - "file if it exists. To append to an existing log file, pass `True` or `1`. " - "To overwrite an existing log file, pass `False`, `0`, or do not add the -a " - "argument. E.g. -a True or -a False.", + help="A boolean option for whether to overwrite or append to an " + "existing log file if it exists. To append to an existing log " + "file, pass `True` or `1`. To overwrite an existing log file, " + "pass `False`, `0`, or do not add the -a argument. E.g. -a True " + "or -a False.", default=False ) @@ -204,7 +211,8 @@ def main() -> None: results, unknown_args = parser.parse_known_args() additional_config = _parse_additonal_config(unknown_args) - bus = _create_bus(results, can_filters=_parse_filters(results), **additional_config) + bus = _create_bus( + results, can_filters=_parse_filters(results), **additional_config) if results.active: bus.state = BusState.ACTIVE @@ -214,25 +222,28 @@ def main() -> None: print(f"Connected to {bus.__class__.__name__}: {bus.channel_info}") print(f"Can Logger (Started on {datetime.now()})") - # argparser.py in Python 3.7.11 does not properly consider boolean arguments passed - # in from the command line. If a boolean is passed in, the variable must be converted - # to an integer 0 (False) or 1 (True). Once the project goes to a minimum of - # Python 3.9, the BooleanOptionalAction can be used and the following code block will - # no longer be required (Please do not use this as a reason to advocate a minimum - # Python version of 3.9). + # argparser.py in Python 3.7.11 does not properly consider boolean + # arguments passed in from the command line. If a boolean is passed in, + # the variable must be converted to an integer 0 (False) or 1 (True). + # Once the project goes to a minimum of Python 3.9, the + # `BooleanOptionalAction` can be used and the following code block will no + # longer be required (Please do not use this as a reason to advocate a + # minimum Python version of 3.9). boolean_args = ['-a', '--append'] args = sys.argv[1:] for i, bool_arg in enumerate(boolean_args): for j, arg in enumerate(args): if bool_arg == arg: - # Make sure the length of args is long enough to check the toggle, e.g. - # stop an index error from occurring. - # argparse.py should have already caught this, but this is a double check + # Make sure the length of args is long enough to check the + # toggle, e.g. stop an index error from occurring. + # argparse.py should have already caught this, but this is a + # double check. if len(args)-1 >= j+1: toggle = args[j+1] else: break - # Consider the action, and update the results to accurately embody request + # Consider the action, and update the results to accurately + # embody request. if toggle == '0' or toggle == 'False': results.append_mode = False elif toggle == '1' or toggle == 'True': @@ -242,9 +253,9 @@ def main() -> None: options = {'append': results.append_mode} if results.file_size: - logger = SizedRotatingLogger( - base_filename=results.log_file, max_bytes=results.file_size, **options - ) + logger = SizedRotatingLogger(base_filename=results.log_file, + max_bytes=results.file_size, + **options) else: logger = Logger(filename=results.log_file, **options) # type: ignore From 7990ff5389b720ec0ebfc6d6dd9eb7d36996a35b Mon Sep 17 00:00:00 2001 From: j-c-cook Date: Tue, 7 Jun 2022 08:41:10 -0500 Subject: [PATCH 08/13] Make formatting recomendations based on `pylint logger.py` --- can/logger.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/can/logger.py b/can/logger.py index 90370aa23..7d95765ec 100644 --- a/can/logger.py +++ b/can/logger.py @@ -231,7 +231,7 @@ def main() -> None: # minimum Python version of 3.9). boolean_args = ['-a', '--append'] args = sys.argv[1:] - for i, bool_arg in enumerate(boolean_args): + for _, bool_arg in enumerate(boolean_args): for j, arg in enumerate(args): if bool_arg == arg: # Make sure the length of args is long enough to check the @@ -244,9 +244,9 @@ def main() -> None: break # Consider the action, and update the results to accurately # embody request. - if toggle == '0' or toggle == 'False': + if toggle in ('0', 'False'): results.append_mode = False - elif toggle == '1' or toggle == 'True': + elif toggle in ('1', 'True'): results.append_mode = True else: pass From 1cf0e732392e27b86c98145ce92f2ab8edf9c6cc Mon Sep 17 00:00:00 2001 From: j-c-cook Date: Tue, 7 Jun 2022 08:44:51 -0500 Subject: [PATCH 09/13] Format code with black logger.py to stop failing the `black` check --- can/logger.py | 67 ++++++++++++++++++++++++--------------------------- 1 file changed, 32 insertions(+), 35 deletions(-) diff --git a/can/logger.py b/can/logger.py index 7d95765ec..9ba614518 100644 --- a/can/logger.py +++ b/can/logger.py @@ -31,10 +31,10 @@ def _create_base_argument_parser(parser: argparse.ArgumentParser) -> None: parser.add_argument( "-c", "--channel", - help=r'Most backend interfaces require some sort of channel. For ' - r'example with the serial interface the channel might be a rfcomm' - r' device: "/dev/rfcomm0". With the socketcan interface valid ' - r'channel examples include: "can0", "vcan0".', + help=r"Most backend interfaces require some sort of channel. For " + r"example with the serial interface the channel might be a rfcomm" + r' device: "/dev/rfcomm0". With the socketcan interface valid ' + r'channel examples include: "can0", "vcan0".', ) parser.add_argument( @@ -50,8 +50,7 @@ def _create_base_argument_parser(parser: argparse.ArgumentParser) -> None: "-b", "--bitrate", type=int, help="Bitrate to use for the CAN bus." ) - parser.add_argument( - "--fd", help="Activate CAN-FD support", action="store_true") + parser.add_argument("--fd", help="Activate CAN-FD support", action="store_true") parser.add_argument( "--data_bitrate", @@ -63,9 +62,9 @@ def _create_base_argument_parser(parser: argparse.ArgumentParser) -> None: "extra_args", nargs=argparse.REMAINDER, help=r"The remaining arguments will be used for the interface " - r"initialisation. For example, `-i vector -c 1 --app-name=" - r"MyCanApp` is the equivalent to opening the bus with `Bus(" - r"'vector', channel=1, app_name='MyCanApp')", + r"initialisation. For example, `-i vector -c 1 --app-name=" + r"MyCanApp` is the equivalent to opening the bus with `Bus(" + r"'vector', channel=1, app_name='MyCanApp')", ) @@ -84,9 +83,9 @@ def _append_filter_argument( "--filter", help="R|Space separated CAN filters for the given CAN interface:" "\n : (matches when & mask ==" - " can_id & mask)" + " can_id & mask)" "\n ~ (matches when & mask !=" - " can_id & mask)" + " can_id & mask)" "\nFx to show only frames with ID 0x100 to 0x103 and 0x200 to 0x20F:" "\n python -m can.viewer -f 100:7FC 200:7F0" "\nNote that the ID and mask are always interpreted as hex values", @@ -98,8 +97,7 @@ def _append_filter_argument( def _create_bus(parsed_args: Any, **kwargs: Any) -> can.Bus: - logging_level_names = \ - ["critical", "error", "warning", "info", "debug", "subdebug"] + logging_level_names = ["critical", "error", "warning", "info", "debug", "subdebug"] can.set_logging_level(logging_level_names[min(5, parsed_args.verbosity)]) config: Dict[str, Any] = {"single_handle": True, **kwargs} @@ -128,8 +126,7 @@ def _parse_filters(parsed_args: Any) -> CanFilters: elif "~" in filt: parts = filt.split("~") can_id = int(parts[0], base=16) | 0x20000000 # CAN_INV_FILTER - can_mask = \ - int(parts[1], base=16) & 0x20000000 # socket.CAN_ERR_FLAG + can_mask = int(parts[1], base=16) & 0x20000000 # socket.CAN_ERR_FLAG else: raise argparse.ArgumentError(None, "Invalid filter argument") can_filters.append({"can_id": can_id, "can_mask": can_mask}) @@ -139,14 +136,15 @@ def _parse_filters(parsed_args: Any) -> CanFilters: def _parse_additonal_config(unknown_args): return dict( - (arg.split("=", 1)[0].lstrip("--").replace("-", "_"), - arg.split("=", 1)[1]) for arg in unknown_args) + (arg.split("=", 1)[0].lstrip("--").replace("-", "_"), arg.split("=", 1)[1]) + for arg in unknown_args + ) def main() -> None: parser = argparse.ArgumentParser( description="Log CAN traffic, printing messages to stdout or to a " - "given file.", + "given file.", ) _create_base_argument_parser(parser) @@ -165,7 +163,7 @@ def main() -> None: dest="file_size", type=int, help="Maximum file size in bytes. Rotate log file when size threshold " - "is reached.", + "is reached.", default=None, ) @@ -176,11 +174,11 @@ def main() -> None: dest="append_mode", type=bool, help="A boolean option for whether to overwrite or append to an " - "existing log file if it exists. To append to an existing log " - "file, pass `True` or `1`. To overwrite an existing log file, " - "pass `False`, `0`, or do not add the -a argument. E.g. -a True " - "or -a False.", - default=False + "existing log file if it exists. To append to an existing log " + "file, pass `True` or `1`. To overwrite an existing log file, " + "pass `False`, `0`, or do not add the -a argument. E.g. -a True " + "or -a False.", + default=False, ) parser.add_argument( @@ -211,8 +209,7 @@ def main() -> None: results, unknown_args = parser.parse_known_args() additional_config = _parse_additonal_config(unknown_args) - bus = _create_bus( - results, can_filters=_parse_filters(results), **additional_config) + bus = _create_bus(results, can_filters=_parse_filters(results), **additional_config) if results.active: bus.state = BusState.ACTIVE @@ -229,7 +226,7 @@ def main() -> None: # `BooleanOptionalAction` can be used and the following code block will no # longer be required (Please do not use this as a reason to advocate a # minimum Python version of 3.9). - boolean_args = ['-a', '--append'] + boolean_args = ["-a", "--append"] args = sys.argv[1:] for _, bool_arg in enumerate(boolean_args): for j, arg in enumerate(args): @@ -238,24 +235,24 @@ def main() -> None: # toggle, e.g. stop an index error from occurring. # argparse.py should have already caught this, but this is a # double check. - if len(args)-1 >= j+1: - toggle = args[j+1] + if len(args) - 1 >= j + 1: + toggle = args[j + 1] else: break # Consider the action, and update the results to accurately # embody request. - if toggle in ('0', 'False'): + if toggle in ("0", "False"): results.append_mode = False - elif toggle in ('1', 'True'): + elif toggle in ("1", "True"): results.append_mode = True else: pass - options = {'append': results.append_mode} + options = {"append": results.append_mode} if results.file_size: - logger = SizedRotatingLogger(base_filename=results.log_file, - max_bytes=results.file_size, - **options) + logger = SizedRotatingLogger( + base_filename=results.log_file, max_bytes=results.file_size, **options + ) else: logger = Logger(filename=results.log_file, **options) # type: ignore From 78a305d3ccfea27f2dc69b098a6aee1b70e3a0e6 Mon Sep 17 00:00:00 2001 From: j-c-cook Date: Wed, 8 Jun 2022 20:37:05 -0500 Subject: [PATCH 10/13] Reduce complexity of append arg parse incorporation --- can/logger.py | 50 ++++++-------------------------------------------- 1 file changed, 6 insertions(+), 44 deletions(-) diff --git a/can/logger.py b/can/logger.py index 9ba614518..b31b34bd3 100644 --- a/can/logger.py +++ b/can/logger.py @@ -157,6 +157,11 @@ def main() -> None: default=None, ) + parser.add_argument("--a", + "--append", + help="Append to the log file if it already exists.", + action="store_true") + parser.add_argument( "-s", "--file_size", @@ -167,20 +172,6 @@ def main() -> None: default=None, ) - parser.add_argument( - "-a", - "--append", - # "action"=argparse.BooleanOptionalAction, # Use when Python>=3.9 - dest="append_mode", - type=bool, - help="A boolean option for whether to overwrite or append to an " - "existing log file if it exists. To append to an existing log " - "file, pass `True` or `1`. To overwrite an existing log file, " - "pass `False`, `0`, or do not add the -a argument. E.g. -a True " - "or -a False.", - default=False, - ) - parser.add_argument( "-v", action="count", @@ -219,36 +210,7 @@ def main() -> None: print(f"Connected to {bus.__class__.__name__}: {bus.channel_info}") print(f"Can Logger (Started on {datetime.now()})") - # argparser.py in Python 3.7.11 does not properly consider boolean - # arguments passed in from the command line. If a boolean is passed in, - # the variable must be converted to an integer 0 (False) or 1 (True). - # Once the project goes to a minimum of Python 3.9, the - # `BooleanOptionalAction` can be used and the following code block will no - # longer be required (Please do not use this as a reason to advocate a - # minimum Python version of 3.9). - boolean_args = ["-a", "--append"] - args = sys.argv[1:] - for _, bool_arg in enumerate(boolean_args): - for j, arg in enumerate(args): - if bool_arg == arg: - # Make sure the length of args is long enough to check the - # toggle, e.g. stop an index error from occurring. - # argparse.py should have already caught this, but this is a - # double check. - if len(args) - 1 >= j + 1: - toggle = args[j + 1] - else: - break - # Consider the action, and update the results to accurately - # embody request. - if toggle in ("0", "False"): - results.append_mode = False - elif toggle in ("1", "True"): - results.append_mode = True - else: - pass - - options = {"append": results.append_mode} + options = {"append": results.a} if results.file_size: logger = SizedRotatingLogger( base_filename=results.log_file, max_bytes=results.file_size, **options From 318d7b466f3cab7b8884e1a155bb379994dc091a Mon Sep 17 00:00:00 2001 From: j-c-cook Date: Wed, 8 Jun 2022 20:40:14 -0500 Subject: [PATCH 11/13] Fix format with `black can/logger.py` --- can/logger.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/can/logger.py b/can/logger.py index b31b34bd3..dd74ea630 100644 --- a/can/logger.py +++ b/can/logger.py @@ -157,10 +157,12 @@ def main() -> None: default=None, ) - parser.add_argument("--a", - "--append", - help="Append to the log file if it already exists.", - action="store_true") + parser.add_argument( + "--a", + "--append", + help="Append to the log file if it already exists.", + action="store_true", + ) parser.add_argument( "-s", From 2c751896e597af6e5969219d136c37a38aed0723 Mon Sep 17 00:00:00 2001 From: j-c-cook Date: Thu, 9 Jun 2022 10:36:52 -0500 Subject: [PATCH 12/13] Change append argparse access from `results.a` to `results.append` --- can/logger.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/can/logger.py b/can/logger.py index dd74ea630..302e97730 100644 --- a/can/logger.py +++ b/can/logger.py @@ -158,8 +158,8 @@ def main() -> None: ) parser.add_argument( - "--a", "--append", + "--a", help="Append to the log file if it already exists.", action="store_true", ) @@ -212,7 +212,7 @@ def main() -> None: print(f"Connected to {bus.__class__.__name__}: {bus.channel_info}") print(f"Can Logger (Started on {datetime.now()})") - options = {"append": results.a} + options = {"append": results.append} if results.file_size: logger = SizedRotatingLogger( base_filename=results.log_file, max_bytes=results.file_size, **options From e17a9f82a9e667175ec7597782a2302f68798bc7 Mon Sep 17 00:00:00 2001 From: j-c-cook Date: Thu, 9 Jun 2022 10:41:14 -0500 Subject: [PATCH 13/13] Add `dest` option to append argument --- can/logger.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/can/logger.py b/can/logger.py index 302e97730..3594427e6 100644 --- a/can/logger.py +++ b/can/logger.py @@ -158,8 +158,9 @@ def main() -> None: ) parser.add_argument( + "-a", "--append", - "--a", + dest="append", help="Append to the log file if it already exists.", action="store_true", )