在python中将文件名作为参数发送到函数模块时出错。如何解决?

2024-09-30 08:30:16 发布

您现在位置:Python中文网/ 问答频道 /正文

#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

Tags: thenameimporttxtaddreadinputopen
1条回答
网友
1楼 · 发布于 2024-09-30 08:30:16

使用exec而不是eval。你知道吗

eval()函数用于计算表达式并返回(不赋值)结果:

>>> x = eval('3+5')
>>> x
>>> 8

exec语句执行包括赋值的语句:

>>> exec 'y = 3 + 5'
>>> y
>>> 8

http://docs.python.org/reference/simple_stmts.html#the-exec-statementhttp://docs.python.org/library/functions.html#eval。你知道吗

另外请注意,您的代码和我的示例使用globals()或模块级命名空间。由于CPython的快速局部优化,exec无法编写局部变量。你知道吗

相关问题 更多 >

    热门问题