是否可以在Python脚本中生成和执行Python代码?[动态Python代码]

Thi*_*ode 3 python code-generation dynamic

我正在处理一些报告(计数),我必须获取不同参数的计数.很简单,但很乏味.

一个参数的示例查询:

qCountsEmployee = (
    "select count(*) from %s where EmployeeName is not null"
     % (tablename)
     )
CountsEmployee = execute_query(qCountsEmployee)
Run Code Online (Sandbox Code Playgroud)

现在我有几百个这样的参数!

我所做的是:创建所有参数的列表并使用快速Python脚本生成它们,然后复制该文本并将其放在主脚本中以避免繁琐的线条.

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 + ')'
Run Code Online (Sandbox Code Playgroud)

虽然这种方法有效,但我想知道如果不是单独的脚本来生成代码行并将粘贴复制到主程序中,我是否可以直接在主脚本中生成它们并让脚本将它们视为代码行?这将使代码更具可读性是我的想法.希望我有道理!谢谢...

glg*_*lgl 5

这是可能的,但在这里没有用.

做一些像

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
Run Code Online (Sandbox Code Playgroud)

你也可以将所有这些放在一个发电机功能中并做到

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(['...']))
Run Code Online (Sandbox Code Playgroud)