Python: Creating an empty file object
Solution 1
Your problem is that you don't assign to the global fil
:
def init(fname):
fil = open(fname, 'w+')
This creates a new local variable called fil
.
If you want to assign to the global variable fil
you need to bring it into the local scope:
def init(fname):
global fil
fil = open(fname, 'w+')
Solution 2
If you want to MAKE your own logging module, then you may want to turn what you already have into a class, so you can import it as a module.
#LoggerThingie.py
import os
import datetime
class LoggerThingie(object):
def __init__(self,fname):
self.fil = open(fname, 'w+')
self.fil.write("# PyIDE Log for" + str(datetime.datetime.now()))
def log(self,strn):
currentTime = datetime.datetime.now()
self.fil.write(str(currentTime) + ' ' + str(os.getpid()) + ' ' + strn)
print str(currentTime) + ' ' + str(os.getpid()) + ' ' + strn
def halt(self):
self.fil.close()
If you did this as a class, you would not have to keep track of globals in the first place (which is generally understood as bad practice in the world of programming: Why are global variables evil? )
Since it is now a module on its own, when you want to use it in another python program you would do this:
from LoggerThingie import LoggerThingie
#because module filename is LoggerThingie.py and ClassName is LoggerThingie
and then use it wherever you want, for example:
x = LoggerThingie('filename.txt') #create LoggerThingie object named x
and every-time you want to insert logs into it:
x.log('log this to the file')
and when you are finally done:
x.halt() # when ur done
Comments
-
Galen Nare almost 2 years
I am attempting to make a logging module for Python that does not work because it fails on creation of the file object.
debug.py:
import os import datetime import globals global fil fil = None def init(fname): fil = open(fname, 'w+') fil.write("# PyIDE Log for" + str(datetime.datetime.now())) def log(strn): currentTime = datetime.datetime.now() fil.write(str(currentTime) + ' ' + str(os.getpid()) + ' ' + strn) print str(currentTime) + ' ' + str(os.getpid()) + ' ' + strn def halt(): fil.close()
fil will not work as
None
as I get anAttributeError
. I also tried creating a dummy object:fil = open("dummy.tmp","w+")
but the
dummy.tmp
file is written to instead, even thoughinit()
is called beforelog()
is. Obviously you cannot open a new file over an already opened file. I attempted to closefil
beforeinit()
, but Python said it could not performwrite()
on a closed file.This is the code that is accessing
debug.py
if os.path.exists(temp): os.rename(temp, os.path.join("logs","archived","log-" + str(os.path.getctime(temp)) + ".txt")) debug.init(globals.logPath) debug.log("Logger initialized!")
I would like to have logging in my program and I cannot find a workaround for this.