| 42 | |
| 43 | |
| 44 | def wc(file_path, args): |
| 45 | if file_path == "-": # read from stdin |
| 46 | content = sys.stdin.read() |
| 47 | mapped_bytes = Str(content) |
| 48 | else: |
| 49 | try: |
| 50 | mapped_file = File(file_path) |
| 51 | mapped_bytes = Str(mapped_file) |
| 52 | except RuntimeError: # File gives a RuntimeError if the file does not exist |
| 53 | return f"No such file: {file_path}", False |
| 54 | |
| 55 | counts = {} |
| 56 | if args.lines: |
| 57 | counts["line_count"] = mapped_bytes.count("\n") |
| 58 | if args.words: |
| 59 | counts["word_count"] = mapped_bytes.count(" ") + 1 |
| 60 | if args.chars: |
| 61 | counts["char_count"] = mapped_bytes.__len__() |
| 62 | |
| 63 | if args.max_line_length: |
| 64 | max_line_length = max(len(line) for line in mapped_bytes.split("\n")) |
| 65 | counts["max_line_length"] = max_line_length |
| 66 | |
| 67 | if args.bytes: |
| 68 | if args.chars: |
| 69 | counts["byte_count"] = counts["char_count"] |
| 70 | else: |
| 71 | counts["byte_count"] = mapped_bytes.__len__() |
| 72 | |
| 73 | return counts, True |
| 74 | |
| 75 | |
| 76 | def format_output(counts, args, just): |