Skip to content

Enhance can.logger to consider the append option #1327

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 14 commits into from
Jun 10, 2022

Conversation

j-c-cook
Copy link
Contributor

@j-c-cook j-c-cook commented Jun 6, 2022

The goal here appears to be to give access to the boolean append option of Printer.

class Printer(MessageWriter):
"""
The Printer class is a subclass of :class:`~can.Listener` which simply prints
any messages it receives to the terminal (stdout). A message is turned into a
string using :meth:`~can.Message.__str__`.
:attr write_to_file: `True` if this instance prints to a file instead of
standard out
"""
file: Optional[TextIO]
def __init__(
self, file: Optional[Union[StringPathLike, TextIO]] = None, append: bool = False
) -> None:
"""
:param file: An optional path-like object or a file-like object to "print"
to instead of writing to standard out (stdout).
If this is a file-like object, is has to be opened in text
write mode, not binary write mode.
:param append: If set to `True` messages, are appended to the file,
else the file is truncated
"""
mode = "a" if append else "w"
super().__init__(file, mode=mode)

closes #1326

@codecov
Copy link

codecov bot commented Jun 6, 2022

Codecov Report

Merging #1327 (e17a9f8) into develop (0c4dee0) will increase coverage by 0.00%.
The diff coverage is 100.00%.

@@           Coverage Diff            @@
##           develop    #1327   +/-   ##
========================================
  Coverage    65.96%   65.97%           
========================================
  Files           86       86           
  Lines         8953     8955    +2     
========================================
+ Hits          5906     5908    +2     
  Misses        3047     3047           

@j-c-cook
Copy link
Contributor Author

j-c-cook commented Jun 6, 2022

Interestingly it looks like Python's argparser.py isn't well suited for a bool option in Python==3.7.13.

The following line is where the issue occurs:

 # convert the value to the appropriate type
        try:
            result = type_func(arg_string)

The reason for the issue can be explained below:

>>> print(bool(0))
False
>>> print(bool(1))
True
>>> print(bool('0'))
True
>>> print(bool('1'))
True

The command line arguments are passed in as strings, and when evaluating bool(<str>) the result is always True.

This solution is only required until Python>=3.9.
can/logger.py Outdated
Comment on lines 214 to 235
# 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
Copy link
Contributor Author

@j-c-cook j-c-cook Jun 6, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added a manual argparse to search for boolean_args and correct the value of results.append_mode.

NOTE: Only required until Python>=3.9
NOTE: Please do not use this as a reason to advocate Python>=3.9.

@j-c-cook j-c-cook marked this pull request as ready for review June 6, 2022 17:29
@j-c-cook
Copy link
Contributor Author

j-c-cook commented Jun 6, 2022

@hardbyte @zariiii9003 This accomplishes what was described in #1326 and is ready for review.

@zariiii9003
Copy link
Collaborator

Could you fix the linters?

@j-c-cook
Copy link
Contributor Author

j-c-cook commented Jun 7, 2022

@zariiii9003 The *lack format is failing here (https://github.com/hardbyte/python-can/runs/6761006357?check_suite_focus=true), but when I run it locally the checks pass.

$ black --check --verbose logger.py
Identified `/home/user/Documents/python-can` as project root containing a .git directory.
Sources to be formatted: "can/logger.py"
logger.py wasn't modified on disk since last run.

All done! ✨ 🍰 ✨
1 file would be left unchanged.

@zariiii9003
Copy link
Collaborator

I guess you are using a different black version. Run pip install -r requirements-lint.txt

@j-c-cook
Copy link
Contributor Author

j-c-cook commented Jun 7, 2022

Could you fix the linters?

@zariiii9003 Done. I'm passing 24/25 checks.

@j-c-cook
Copy link
Contributor Author

j-c-cook commented Jun 7, 2022

@zariiii9003 Do you want for me to add in tests to try to resolve the https://github.com/hardbyte/python-can/pull/1327/checks?check_run_id=6775694757 failure?

can/logger.py Outdated
@@ -201,12 +219,42 @@ 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
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You don't need any of this. Look at how the --fd argument is handled. It is also a boolean.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree. I have modified my changes. This simplifies things. Thank you.

@j-c-cook
Copy link
Contributor Author

j-c-cook commented Jun 9, 2022

@zariiii9003 I committed your recommendations. Next time you do that I'll make sure to accept them from this UI rather than manually change them.

@j-c-cook j-c-cook requested a review from zariiii9003 June 9, 2022 15:46
@zariiii9003 zariiii9003 merged commit 1430154 into hardbyte:develop Jun 10, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Enhance the can.logger to check to see if the log file exists and append if there rather than overwrite
2 participants