执行python代码并评估/测试结果

时间:2020-08-18 15:02:39

标签: python

诚然,我不确定如何问这个问题,因为我知道如何在R中处理这个问题(在新环境中执行代码),但是对python解决方案的等效搜索并没有产生我希望的结果。

简而言之,我将收到一个电子表格(或csv),其中该列的内容将包含有效的python代码。这可能等效于脚本,但只包含在csv / workbook中。对于一个用例,请考虑教学编程,其输出是LMS。

我希望做的是遍历文件,并为每个单元运行代码,并将结果存储在内存中,测试一下是否存在某些东西。

例如:https://docs.google.com/spreadsheets/d/1D-zC10rUTuozfTR5yHfauIGbSNe-PmfrZCkC7UTPH1c/edit?usp=sharing

在评估上面电子表格中的第一个响应时,我想测试x,y和z是否都正确定义并具有期望值。

因为文件中有多行,每位学生一行,所以我如何分别运行每一行,评估结果,并确保将结果仅隔离到该单元格。简而言之,继续前进时,我不会保留任何以往的评估。

1 个答案:

答案 0 :(得分:2)

(我不知道执行代码检查的工具,因此我以非常手动的方式进行处理。)

可以使用Python的exec()函数执行字符串,例如单元格中的内容。

例如:

variables = {}
exec("""import os

# a comment
x = 2 
y = 6
z = x * y""", variables)
assert variables["z"] == 12

处理csv文件:

import csv

csv_file = open("path_to_csv_file", "rt")
csv_reader = csv.reader(csv_file)
iterator = iter(csv_reader)
next(iterator) # To skip the titles of the columns

for row in iterator:
    user = row[0]
    answer = row[1]

### Any other code involving the csv file must be put here to work properly,
### that is, before closing csv_file.

csv_file.close() # Remember to close the file.

它将无法检测是否导入了某些模块(因为从exec()函数导入时,该模块将保留在缓存中供下一个执行程序使用)。一种测试方法是“取消导入”模块并测试exec的异常。 例如:

# This piece of code would be before closing the file,
# INSIDE THE FOR LOOP AND WITH IT IDENTED (Because you want
# it to run for each student.).

try:
    del os # 'unimporting' os (This doesn't 'unimport' as much as deletes a
           # reference to the module, what could be problematic if a 'from
           # module import object' statement was used.)
except NameError: # So that trying to delete a module that wasn't imported
                  # does not lead to Exceptions being raised.
    pass

namespace = dict()
try:
    exec(answer, namespace)
except:
    # Answer code could not be run without raising exceptions, i.e., the code
    # is poorly written.

    # Code you want to run when the answer is wrong.
else:
    # The code hasn't raised Exceptions, time to test the variables.

    x, y, z = namespace['x'], namespace['y'], namespace['z']
    if (x == 2) and (y == 6) and (z == x * y):
        # Code you want to run when the answer is right.
    else:
        # Code you want to run when the answer is wrong.

我认为这不是执行此操作的最佳方法,但肯定是一种尝试。 希望对您有所帮助。

编辑:删除了一些错误的代码并添加了Tadhg McDonald-Jensen评论的一部分。