在 Python 中自动执行用户输入

Automating User Input in Python

我想 test/fuzz 我的程序 aba.py,它在几个地方要求用户通过 input() 函数输入。我有一个文件 test.txt,其中包含示例用户输入 (1,000+),每个输入都在一个新行上。我希望 运行 程序将这些输入传递给 aba.py 并记录响应,即它打印出的内容以及是否出现错误。我开始用以下方法解决这个问题:

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

这只是解决方案的一半,因为它 运行 直到遇到错误并且不会将响应记录在单独的文件中。这个问题的最佳解决方案是什么?感谢您的帮助。

你可以这样做:

cat test.txt | python3 aba.py > out.txt

有多种方法可以解决您的问题。

#1:函数

让你的程序成为一个函数(包装整个东西),然后将它导入你的第二个 python 脚本(确保 return 输出)。示例:

#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])

或者,您可以坚持使用终端方法: (参见 this SO post

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