Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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...

like image 336
ThinkCode Avatar asked Jan 19 '23 05:01

ThinkCode


2 Answers

It would be possible, but is not useful here.

Just do something like

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

results = {}
for column in columnList:
    query = (
            "select count(*) from " + tablename
            + " where " + column + " is not null"
            )
    result = execute_query(qCountsEmployee)
    results[column] = result

You as well can put all this together in a generator function and do

def do_counting(column_list):
    for column in column_list:
        query = (
            "select count(*) from " + tablename
            + " where " + column + " is not null"
            )
        result = execute_query(qCountsEmployee)
        yield column, result

result_dict = dict(do_counting(['...']))
like image 128
glglgl Avatar answered Jan 28 '23 15:01

glglgl


You can do:

cmd = compile( 'a = 5', '<string>', 'exec' )
exec( cmd )

That is the same as just writing:

a = 5

The string passed as the first argument to compile can be built dynamically.

like image 43
William Pursell Avatar answered Jan 28 '23 16:01

William Pursell