[Python] Is it possible to generate and execute Python code in a Python script? [Dynamic...

Discussão em 'Python' iniciado por Stack, Maio 3, 2025.

  1. Stack

    Stack Membro Participativo

    I am working on some reports (counts) and I have to fetch counts for different parameters. Pretty simple but tedious.

    A sample query for one parameter :

    qCountsEmployee = (
    "select count(*) from %s where EmployeeName is not null"
    % (tablename)
    )
    CountsEmployee = execute_query(qCountsEmployee)


    Now I have few hundred such parameters!

    What I did was : create a list of all the parameters and generate them using a quick Python script and then copy that text and put it in the main script to avoid the tedious lines.

    columnList = ['a', 'b', ............'zzzz']

    for each in columnList:
    print (
    'q' + each + ' ='
    + '"select count(*) from %s where' + each
    + 'is not null" % (tablename)'
    )
    print each + ' = execute_query(' + 'q' + each + ')'


    While this approach works, I was wondering if instead of a separate script to generate lines of code and copy paste into main program, can I generate them in the main script directly and let the script treat them as lines of code? That will make the code much more readable is what I think. Hope I made sense! Thank you...

    Continue reading...

Compartilhe esta Página