在Python中自动化用户输入

6 浏览
0 Comments

在Python中自动化用户输入

这个问题已经有了答案如何使用文件作为子进程的标准输入输出

我想测试/模糊测试我的程序, aba.py,在几个地方通过input()函数请求用户输入。 我有一个文件test.txt,其中包含样例用户输入(超过1,000个),每个输入都在新行上。 我希望传递这些输入到aba.py并记录响应,即它打印出什么,以及是否引发错误。 我开始用以下方法解决:

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

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

admin 更改状态以发布 2023年5月21日
0
0 Comments

你可以这样做:

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

0
0 Comments

解决问题的方法有很多种。

#1:函数

将您的程序封装为函数(包裹整个程序),然后在第二个Python脚本中导入它(请确保返回输出)。 例如:

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

或者,您可以坚持终端方法:
(参见此SO帖子

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

0