【问题标题】:Automating User Input in Python [duplicate]在 Python 中自动化用户输入 [重复]
【发布时间】:2021-07-24 04:41:22
【问题描述】:

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

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

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

【问题讨论】:

  • 您想为自己的输入输入一个值吗?
  • 在 python 中这样做是必需的吗?例如,bash$ python aba.py < test.txt > output.txt 2> errors.txt 不起作用吗?如果在 python 中是必需的,那么你应该尝试使用subprocess (docs.python.org/3/library/subprocess.html) 而不是os.system,这样你就可以check_output

标签: python input os.system fuzzing


【解决方案1】:

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

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

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

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

【讨论】:

    【解决方案2】:

    你可以这样做:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-24
      • 1970-01-01
      • 1970-01-01
      • 2018-05-06
      • 1970-01-01
      相关资源
      最近更新 更多