Python 2.7导入混乱

时间:2012-03-08 08:20:18

标签: import 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键,结果是在shell上写了“log something”,但是没有创建文件,如果文件已经存在则没有写入文件。

请帮忙。

1 个答案:

答案 0 :(得分: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()