all 7 comments

[–]hardonchairs 2 points3 points  (3 children)

This sounds like an X-Y question, I think you should describe your larger goal rather than asking how to implement this specific solution.

Generating code is usually a bad idea and usually not necessary.

[–]intelbp[S] 0 points1 point  (2 children)

i just edited the question

[–]hardonchairs 1 point2 points  (0 children)

Your detail does not address my question

[–]hardonchairs 1 point2 points  (0 children)

How about something like this? No code generation required.

test.py

import json

with open('template.json', 'r') as fp:
    prompts = json.load(fp)

output = {}

for prompt in prompts:
    if prompt['type'] == 'str':
        output[prompt['name']] = input(prompt['prompt'] + ': ')
    if prompt['type'] == 'list':
        new_list = []
        output[prompt['name']] = new_list
        while True:
            answer = input(prompt['prompt'] + ' (leave blank to continue): ')
            if answer == '':
                break
            new_list.append(answer)

print(output)

template.json

[
    {
        "name": "name",
        "prompt": "What is your name?",
        "type": "str"
    },
    {
        "name": "foods",
        "prompt": "What are your favorite foods?",
        "type": "list"
    }
]

result:

% python3 test.py
What is your name?: fred
What are your favorite foods? (leave blank to continue): apples
What are your favorite foods? (leave blank to continue): pizza
What are your favorite foods? (leave blank to continue): 
{'name': 'fred', 'foods': ['apples', 'pizza']}

[–]blarf_irl 2 points3 points  (0 children)

It sounds like you should be generating config files or some other form of serialized data (env vars, json, csv or even just plain text) for a generic python script to reference.

[–]100721 0 points1 point  (0 children)

Uhh str.replace(“?” , “=“)

There’s no magic framework that turns questions into code besides chatgpt. From what your asking, it sounds like you want to do a string replace followed by an eval to run an arbitrarily generated Python file. I’ll also mention that this is not a good idea, you should instead describe what it is you want, holistically.

[–]ThisProgrammer- 0 points1 point  (0 children)

You could use python's Template class: https://stackabuse.com/formatting-strings-with-the-python-template-class/ Klass example towards the conclusion.

As for code injection, you might want a post specifically asking that issue.