2012-03-08 96 views
0

我试图运行下面的脚本:Python 2.7版进口混乱

#Contents of logging.py 
import sys 
import os 


global gLogfile 
global gLogFileFlag 

#----------------------------------------------------------------------------------------- 
def initLogging(): 
    global gLogFileFlag 
    try: 
     glogFile = 'D:\logggggging.log' 
     print gLogFile 
     fileObject = open(gLogFile, 'w') 
     gLogFileFlag = True 
     fileObject.close() 
    except: 
     gLogFileFlag = False 



#----------------------------------------------------------------------------------------- 
def logIt(text): 
    sys.stdout.write(text) 
    if(gLogFileFlag): 
     hFile = open(gLogFile, 'a') 
     hFile.write(text) 
     hFile.close() 


#----------------------------------------------------------------------------------------- 


#contents of test_defualt.py 
from logging import initLogging 
from logging import logIt 

def main(): 
    initLogging() 
    logIt("log something") 

main() 

当我执行上面的代码,使用F5键,结果是“日志的东西”被写在外壳,但有没有创建文件,如果它已经存在,文件上没有写入任何内容。

请帮忙。

+0

我真的很抱歉,我已经意识到了错误。这是命名,并且在编辑变量时不使用全局关键字。现在工作很好。谢谢。 – Vinayaka 2012-03-08 08:47:19

回答

1

您使用普通的except语句掩盖了您的拼写错误。如果你想检查没有被写入try语句的文件,可以使用类似IOError的东西。

一个工作logging.py(对于那些谁没有看到的错误中的例子):

import sys 
import os 

#----------------------------------------------------------------------- 
def initLogging(): 
    global gLogFileFlag 
    global gLogFile 
    try: 
     gLogFile = './logggggging.log' 
     print gLogFile 
     fileObject = open(gLogFile, 'w') 
     gLogFileFlag = True 
     fileObject.close() 
    except IOError: 
     gLogFileFlag = False 

#------------------------------------------------------------------------ 
def logIt(text): 
    sys.stdout.write(text) 
    if(gLogFileFlag): 
     hFile = open(gLogFile, 'a') 
     hFile.write(text) 
     hFile.close()