Last active
March 4, 2022 23:50
-
-
Save hexpunk/3de4b0c6f74c48943cffde5d43860162 to your computer and use it in GitHub Desktop.
Print the cartesian product of the lines in FILE(s) multiplied with itself REPEAT times to standard output
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import argparse | |
import itertools | |
import os | |
import sys | |
def positive_int(string): | |
"""Return a positive int from the argument string or raise an ArgumentTypeError""" | |
try: | |
value = int(string) | |
except ValueError: | |
msg = "invalid integer value: %r" % string | |
raise argparse.ArgumentTypeError(msg) | |
if not value > 0: | |
msg = "invalid integer, must be greater than 0, received: %r" % string | |
raise argparse.ArgumentTypeError(msg) | |
return value | |
def main(): | |
parser = argparse.ArgumentParser( | |
description=""" | |
Print the cartesian product of the lines in FILE(s) multiplied with itself REPEAT times to standard output. | |
""" | |
) | |
parser.add_argument( | |
"repeat", | |
type=positive_int, | |
help="number of times to multiply the concatenation of FILE(s) with itself", | |
metavar="REPEAT", | |
) | |
parser.add_argument( | |
"files", | |
nargs="*", | |
type=argparse.FileType("r"), | |
default=[sys.stdin], | |
help="""files to read as input; with no FILE or when FILE is "-", standard input is read instead""", | |
metavar="FILE", | |
) | |
parser.add_argument( | |
"-s", | |
"--separator", | |
default="", | |
help="optional string used to delimit the elements in each permutation", | |
) | |
args = parser.parse_args() | |
# https://docs.python.org/3/library/signal.html#note-on-sigpipe | |
try: | |
lines = [line.rstrip("\n") for file in args.files for line in file] | |
for permutation in itertools.product(lines, repeat=args.repeat): | |
print(args.separator.join(permutation)) | |
sys.stdout.flush() | |
except BrokenPipeError: | |
devnull = os.open(os.devnull, os.O_WRONLY) | |
os.dup2(devnull, sys.stdout.fileno()) | |
sys.exit(1) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment