创建要在Python中全局使用的类对象
我编写了下面的模块,该模块将标准化日志文件的编写方式,并可以轻松更改事件是否打印/写入日志文件创建要在Python中全局使用的类对象,python,Python,我编写了下面的模块,该模块将标准化日志文件的编写方式,并可以轻松更改事件是否打印/写入日志文件 FILE: Logging.py ================ import os import datetime import io class Logfile(): def __init__(self,name): self.logFile = os.getcwd() + r'\.Log\\' + name + '_' + str(date
FILE: Logging.py
================
import os
import datetime
import io
class Logfile():
def __init__(self,name):
self.logFile = os.getcwd() + r'\.Log\\' + name + '_' + str(datetime.date.today().year) + ('00' + str(datetime.date.today().month))[-2:] + '.log'
self.printLog = False
self.debug = False
# Setup logFile and consolidated Folder
if not os.path.exists(os.path.dirname(self.logFile)):
os.mkdir(os.path.dirname(self.logFile))
#Check if logfile exists.
if not os.path.exists(self.logFile):
with open(self.logFile, 'w') as l:
pass
# Write LogFile Entry
def logEvent(self, eventText, debugOnly): # Function to add an event to the logfile
# If this is marked as debugging only AND debugging is off
if debugOnly == True and self.debug == False:
return
if self.printLog == True:
print(datetime.datetime.strftime(datetime.datetime.now(), '%m/%d/%Y, %I:%M:%S %p, ') + str(eventText))
with open(self.logFile, 'a') as l:
l.seek(0)
l.write(datetime.datetime.strftime(datetime.datetime.now(), '%m/%d/%Y, %I:%M:%S %p, ') + str(eventText) + '\n')
return
这是非常方便的,但是,我很难理解如何使我的所有课程都可以使用它。例如,如果导入以下模块,我不确定如何使用在主脚本中创建的日志文件
FILE: HelloWorld.py
===================
class HelloWorld():
def __init__(self):
log.logEvent('You have created a HelloWorld Object!', False)
此处的主脚本:
import Logging
from HelloWorld import HelloWorld
log = logging.Logfile
hw = HelloWorld()
^^将失败,因为它不知道日志是一种东西。处理这种情况的正确方法是什么?我相信你正在尝试这样做。(作为补充说明,您可能希望研究使用pythons默认日志记录模块)
此外,要创建模块,您需要在给定目录中添加一个
\uuu init\uuuu.py
文件。使用内置的“日志”模块可以轻松解决此问题。在回答更广泛的“如何在我的所有模块中使用一个东西(日志)”问题时,我假设可以通过阅读日志模块中的代码并模仿它来找到答案。在旁注中,你为什么要重新发明轮子import logging
正如DeepSpace所说,已经有了这个模块,您可以创建一个函数,根据需要设置所有参数,只需使用它或导入即可。如果您确实想要全局模块,您应该尝试使用pip install-e安装它。
为此,您需要指定setup.py如果class HelloWorld():
在另一个模块中,那么它将抛出异常,除非我将log
传递给它。
FILE: HelloWorld.py
===================
# import LogFile
from .Logging import LogFile
# create new LogFile instance
log = LogFile(name='log name')
class HelloWorld():
def __init__(self):
# call logEvent method on your LogFile instance
log.logEvent('You have created a HelloWorld Object!', False)
FILE: Main.py
===================
# import HelloWorld
from .HellowWorld import HellowWorld
# create new HellowWorld instance
hw = HellowWorld()