Search code examples
pythoninputos.systemfuzzing

Automating User Input in Python


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.


Solution

  • 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