我正在尝试运行以下脚本:
#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键执行上面的代码时,结果是"log something“写在外壳上,但是没有创建任何文件,如果文件已经存在,也不会写入任何内容。
请帮帮忙。
发布于 2012-05-15 15:59:13
您使用普通的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()https://stackoverflow.com/questions/9614642
复制相似问题