shioko
shioko

Reputation: 312

Stream file content as program input

I'm solving some coding challenges.

How can I create (use) a program (2) that runs the program (1), takes a text file (input.txt) content as input (3), feeds the input to program (1), gets output (4), and compares (4) to the output.txt file content (desired output).

Addition information

Here is what I have been doing.

Sample program

def add(a, b):
  # return a + b
  return a + b + 1

if __name__ == '__main__':
  a = int(input())
  b = int(input())
  retval = add(a, b)
  print(retval)
1
2
3

Goal

Upvotes: 0

Views: 67

Answers (1)

Toothpick Anemone
Toothpick Anemone

Reputation: 4644

You can shadow the input function, and then run the program. The new input function won't ask the human user for input. Instead, input will read the input from a file.

import pathlib as pl

def get_integers_from_file(path):
    path = pl.Path(str(path))
    lyst = list()
    with open(str(path), mode="r") as inf:
        for line in inf:
            lyst.append(int(line.strip()))
    return lyst

inputs = get_integers_from_file("input.txt")
output = get_integers_from_file("output.txt.py")

class InputHijacker:
    def __init__(self, inputs):
        self._inputs = inputs
        self._state = 0
    def __call__(i):
        r = i._inputs[i._state]
        i._state += 1
        return r

class PrintHijacker:
    print = print
    def __init__(self, file_path):
        file_path = str(pl.Path(str(file_path)))
        self._file = open(file_path, mode="w")

    def __call__(self, *args, sep=" ", end="\n", file=""):
        # discard/ignore input argument `file`
        return type(self).print(*args, sep=sep, end=end, file=self._file)

    def __del__(self):
        self._file.close()

input = InputHijacker(inputs)
# `input` no longer prompts the user
print = PrintHijacker("program_output.txt")
# `print` no longer prints output to sys.stdout

def add(a, b):
  # return a + b
  return a + b + 1

##################################################################################

if __name__ == '__main__':
  a = int(input())
  b = int(input())
  retval = add(a, b)
  print(retval)

  correct_out = get_integers_from_file("output.txt.py")
  program_out = get_integers_from_file("program_output.txt")
  for idx in range(len(program_out)):
      assert(correct_out[idx] == program_out[idx])

Upvotes: 1

Related Questions