Better argument parsing, added -n/--number option (from cat)

This commit is contained in:
Lavender Perry 2021-11-21 16:27:00 -08:00
parent fc1bc20b2d
commit 25231e4fbb
Signed by untrusted user: elle
GPG key ID: EF8E44AF715C28A0

77
pat.py
View file

@ -1,39 +1,54 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
from enum import IntEnum from enum import IntEnum
from sys import argv, stdin, stderr from sys import stdin, stderr
from string import whitespace from string import whitespace
import argparse
# These next 2 lines of code are only for ANSI escape support on Windows cmd/powershell import os
# If you do not use cmd/ps, you can comment them out or remove them
from os import system
system("")
# If the program is using too much memory, try decreasing this value
bytes_to_read = 1000000
class ColorInfo(IntEnum): class ColorInfo(IntEnum):
AMOUNT = 299 AMOUNT = 299 # Amount of colors to be outputted (must not be higher than PER_STAGE)
MAX_RGB_VALUE = 255 MAX_RGB_VALUE = 255 # Max value any r/g/b can have
# Do not change these next 2
PER_STAGE = (AMOUNT + 1) // 3 PER_STAGE = (AMOUNT + 1) // 3
MIN_RGB_VALUE = MAX_RGB_VALUE - PER_STAGE MIN_RGB_VALUE = MAX_RGB_VALUE - PER_STAGE
# If the program is using too much memory, try decreasing this value
# If some text is getting cut off, try increasing this value
bytes_to_read = 1000000
if len(argv) == 1: first_file = True
argv.append("-")
for arg in argv[1:]: line_str = lambda line: str(line).rjust(8, ' ') + ' '
color_print = lambda red, green, blue, string: print(
"\x1b[38;2;%d;%d;%dm%s" % (red, green, blue, string),
end='')
parser = argparse.ArgumentParser(description="Output text from files with color.")
parser.add_argument(
"paths",
type=str,
nargs='*',
help="a path to open ('-' for stdin)",
default=['-'])
parser.add_argument(
"-n", "--number",
help="number all output lines",
action="store_true")
args = parser.parse_args()
line = 1 if args.number else False
# Windows command prompt / powershell support
if os.name == "nt":
os.system('')
for path in args.paths:
try: try:
file = stdin if arg == "-" else open(arg, "r") file = stdin if path == '-' else open(path, 'r')
read_result = file.read(bytes_to_read) read_result = file.read(bytes_to_read)
except Exception as e: except Exception as e:
print( print(f"Error reading {path}: {e}", file=stderr)
"Error "
+ (f"reading {file.name}" if "file" in globals() else "opening file")
+ f": {e}",
file=stderr,
)
continue continue
changes = len(list(filter(lambda c: not c in whitespace, read_result))) - 1 changes = len(list(filter(lambda c: not c in whitespace, read_result))) - 1
@ -41,9 +56,20 @@ for arg in argv[1:]:
step = 0 if changes == 0 else ColorInfo.AMOUNT / changes step = 0 if changes == 0 else ColorInfo.AMOUNT / changes
index = 0 index = 0
if line and first_file:
color_print(
ColorInfo.MAX_RGB_VALUE,
ColorInfo.MIN_RGB_VALUE,
ColorInfo.MIN_RGB_VALUE,
line_str(line))
for char in read_result: for char in read_result:
if char in whitespace: if char in whitespace:
print(char, end="") print(char, end='')
if line and char == '\n':
line += 1
print(line_str(line), end='')
continue continue
color_value = round(index) color_value = round(index)
@ -59,7 +85,6 @@ for arg in argv[1:]:
[rgb_values[0], rgb_values[2], rgb_values[1]], [rgb_values[0], rgb_values[2], rgb_values[1]],
][color_value // ColorInfo.PER_STAGE] ][color_value // ColorInfo.PER_STAGE]
print("\x1b[38;2;%d;%d;%dm%s" % (red, green, blue, char), end="") color_print(red, green, blue, char)
index += step index += step
print("\x1b[0m") print("\x1b[0m")