我希望在Codeacademy上写一门基本的生物信息学课程。他们有一个很好的编写课程的界面,但是测试有点慢,因为必须保存,然后预览,然后运行。
所以我想写一个模仿他们的小测试环境。它的工作方式似乎是将用户输入代码作为字符串读入函数,str
代码中的所有实例都转换为unicode
(我刚刚为此使用了正则表达式),然后使用exec
.
棘手的部分似乎是当我想合并Submission Test时。
提交测试需要返回True
, False
, 或 a str
, 并且被写成函数的主体。例如:
我想要做的简化版本:
# The submission test must be a function.
def test_code(code, CC, error):
# Use information from errors in student code
if error:
return "Yada yada %s" %error
# Use information in the raw student code
if len(code.split("\n")) is not 2:
return "This should be accomplished in 2 lines"
# Have direct access to variables from the student code
# I'd like to avoid params['y'] if possible.
try:
y
except NameError:
return "Please use the variable y"
if y is not 8:
return "Wrong! Check stuff"
# Use information from print output
if str(y) not in CC:
return "Remember to print your variable!"
return True
# Read in student code
student_code = """y = 8
print y
potato"""
# Catch print output
CC = StringIO.StringIO()
sys.stdout = CC
# Execute student code and catch errors
try:
exec student_code
except Exception as e:
error = e
# Start outputting to the terminal again
sys.stdout = sys.__stdout__
# Run the submission test
submission_test = test_code(student_code, CC.split("\n"), error)
# Output the result of the submission test
if submission_test is True:
print("Well done!")
elif submission_test is False:
print("Oops! You failed... Try again!")
else:
print(submission_test)
但是,我似乎无法从中获取变量exec code
以传递给提交测试函数(test_code
在这种情况下)。
我可以在提交测试中执行代码,但如果可能的话,我想避免这种情况,否则必须将它添加到每个测试中,这看起来很不合python!
任何帮助将不胜感激 :)