2012-03-29 107 views
0

我有两个函数,我将其中一个函数放入了一个单独的.py文件,所以我可以导入它,但是当我尝试运行脚本时出现错误。NameError:没有定义全局名称'myLogFile'

,我放入单独的.py功能是:

def output_messaging(message): 
    global myEmailText 
    myLogFile.write(message) 
    myEmailText = myEmailText + message 
    print message 

,我运行具有以下代码的脚本:

def finish_process(errors): 
    global myLogFile 
    myLogFile.close() 
    if errors == 0: 
     myEmailHeader = "Subject: **" 
    elif errors == 1: 
     myEmailHeader = "Subject: **" 
    else: 
     myEmailDestination.append("**") 
     #myEmailHeader = "Subject: **" 
    server = smtplib.SMTP(myServer) #email data log to nominated individuals 
    server.sendmail(myEmailSender, myEmailDestination, myEmailHeader + "\n" + myEmailText) 
    server.quit() 

当我运行该脚本,我碰到下面的错误。

NameError: global name 'myLogFile' is not defined 

myLogFile在代码(这是日志文件的位置)中声明较低,但我有点困惑。

谢谢

+0

如果您向我们展示了一个完整,简短的示例来说明问题,我们将能够告诉您究竟*问题是什么...... – NPE 2012-03-29 14:31:43

+0

错误的行号? – 2012-03-29 14:35:49

+0

output_messaging中的第4行文件“D:\ temp \ UFRM \ messaging.py” myLogFile.write(message) NameError:全局名称'myLogFile'未定义 – MapMan 2012-03-29 14:44:10

回答

1

错误很明显。 myLogFile在您的output_messaging函数的任何地方都没有定义。您需要在该函数中定义它,或者将其作为参数传递。

无论如何,你不应该使用全局变量,它们几乎总是一个坏主意。明确传递参数。

+0

我在output_messaging函数中添加了全局myLogFile,但它仍然给我同样的错误。 – MapMan 2012-03-29 14:39:07

-1

output_messaging中,您没有global myLogFile指示myLogFile在文件的其他位置定义。当Python运行该函数时,它现在不能识别变量。

请注意,全局变量通常是不鼓励的,但这是一个不同的讨论。

相关问题