简体   繁体   中英

Automated user input from file for testing purposes in python

I feel like I am lacking the terminology to properly search for answers to my question, so any hint in the right direction would be greatly appreciated.

I have a script that takes multiple (>30) user inputs to create a json file using a jinja2 template. It happens quite often that I need to add stuff both to the python code as well as the jinja2 template. For each change there are generally 4-5 different user inputs possible.

Rather than entering the >30 user inputs manually every time, I'd like to automate this. Is there a way to, for example, create a text file that lists the >30 user inputs and iterate over this file?

Example below:

    question1 = input('How much is 1+1?')
    question2 = input('Will I find an answer to my problem?')
    question3 = input('What should be the next question?')

Then the file with the answers would look like:

    2
    If you are lucky
    No idea

If at all possible, I would like to only have to do minimal modifications to the code.

You are looking for something like pickle or json. Json will be more legible should you choose to edit these in the text editor.

import json

answers = {'question1': 2, 'question2': 'If you are lucky'}
with open('answer_log.txt', 'w') as file:
    file.write(json.dumps(answers))

Then to load the file you call:

with open('answer_log.txt', 'r') as file:
    answers = json.loads(file.read())

This creates an easily editable text file that will look something like:

'{"question1": 2...........}'

Now you have a python dictionary you can easily iterate over to automate your process.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM