#This code does the checking of the function input.
import re
import sys
def pyexam(file_name):
fp = open(file_name)
testCaseInput = open('input.txt','r')
testCaseOutput = open('output.txt','r')
eval(compile(fp.read(),'prob.txt','exec'))
if add(int(testCaseInput.read())) == int(testCaseOutput.read()):
print "yes"
else:
print "no"
file_name ='prob.txt'
pyexam(file_name)
文件prob.txt文件有一个add模块。你知道吗
这在不将其包含在函数中的情况下工作。另外,当我将文件名作为参数发送时,它也可以工作。因此,当我将文件名作为参数发送给函数模块时,它为什么不工作,这是非常令人困惑的。我得到的错误是:
File "exam.py", line 13, in pyexam
if add(int(testCaseInput.read())) == int(testCaseOutput.read()):
NameError: global name 'add' is not defined
使用exec而不是eval。你知道吗
eval()函数用于计算表达式并返回(不赋值)结果:
exec语句执行包括赋值的语句:
见http://docs.python.org/reference/simple_stmts.html#the-exec-statement和http://docs.python.org/library/functions.html#eval。你知道吗
另外请注意,您的代码和我的示例使用globals()或模块级命名空间。由于CPython的快速局部优化,exec无法编写局部变量。你知道吗
相关问题 更多 >
编程相关推荐