Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to give input to python console and validate the output programmatically?

For this sample program

N = int(raw_input());
n  = 0;
sum = 0;
while n<N:

    sum += int(raw_input());
    n+=1;

print sum;  

I have a set of testcases, so I need a python program that invokes the above python program, gives input and should validate the output printed in the console.

like image 410
Sathish Avatar asked Sep 02 '25 03:09

Sathish


1 Answers

In a Unix shell, this can be achieved by:

$ python program.py < in > out  # Takes input from in and treats it as stdin.
                                # Your output goes to the out file.
$ diff -w out out_corr          # Validate with a correct output set

You can do the same in Python like this

from subprocess import Popen, PIPE, STDOUT

f = open('in','r')            # If you have multiple test-cases, store each 
                              # input/correct output file in a list and iterate
                              # over this snippet.
corr = open('out_corr', 'r')  # Correct outputs
cor_out = corr.read().split()
p = Popen(["python","program.py"], stdin=PIPE, stdout=PIPE)
out = p.communicate(input=f.read())[0]
out.split()
# Trivial - Validate by comparing the two lists element wise.
like image 56
sidi Avatar answered Sep 05 '25 00:09

sidi