3

I would like to test/fuzz my program, aba.py, which in several places asks for user input via the input() function. I have a file, test.txt, with the sample user inputs (1,000+) with each input on a new line. I wish to run the program with these inputs passed to the aba.py and record the response i.e. what it prints out and if an error is raised. I started to solve this with:

os.system("aba.py < test.txt")

This is only a half solution as it runs until an error is encountered and doesn't record the response in a separate file. What would be the best solution to this problem? Thank you for your help.

al512
  • 55
  • 3
  • You want to enter an value for your own input? – Buddy Bob Apr 30 '21 at 21:29
  • 1
    Is doing this in python a requirement? As in, does `bash$ python aba.py < test.txt > output.txt 2> errors.txt` not work? If in python is a requirement, then you should try using `subprocess` (https://docs.python.org/3/library/subprocess.html) instead of `os.system`, which lets you `check_output` – Hrishikesh Apr 30 '21 at 21:44

2 Answers2

0

you can do it this way:

cat test.txt | python3 aba.py > out.txt
Moein
  • 167
  • 3
  • 11
0

There are a number of ways to solve your problem.

#1: Functions

Make your program a function (wrap the entire thing), then import it in your second python script (make sure to return the output). Example:

#aba.py
def func(inp):
    #Your code here
    return output
#run.py
from aba import func
with open('inputs.txt','r') as inp:
    lstinp = inp.readlines()
out = []
for item in lstinp:
    try:
        out.append(func())
    except Exception as e:
        #Error
        out.append(repr(e))
with open('out.txt','w') as out:
    out.writelines(['%s\n' % item for item in out])

Alternatively, you could stick with the terminal approach: (see this SO post)

import subprocess
#loop this
output = subprocess.Popen('python3 aba.py', stdout=subprocess.PIPE).communicate()[0]
#write it to a file
bobtho'-'
  • 128
  • 2
  • 8