与文件同名的导入模块 [英] importing module with same name as file
本文介绍了与文件同名的导入模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要导入日志记录 https://docs.python.org/3/library /logging.html 放入名为logging.py的文档中.但是,当我尝试导入logging.handlers时,它失败了,因为我认为它是在文档中搜索处理程序功能,而不是从模块中导入.如何解决此问题,以便它将查找更高级别的日志记录,而不是查找文件内部?
I want to import logging https://docs.python.org/3/library/logging.html into a document named logging.py . When I try to import logging.handlers though, it fails because I believe it's searching the document for a handlers function, instead of importing from the module. How can I fix this so it will look for the higher level logging instead of looking inside the file?
推荐答案
您可以通过从python路径中删除当前目录(sys.path中的第一个目录)来实现此目的:
You can do it by removing current directory (first in sys.path) from python path:
import sys
sys.path = sys.path[1:]
import logging
print dir(logging)
测试:
$ python logging.py
['BASIC_FORMAT', 'BufferingFormatter', 'CRITICAL', 'DEBUG', 'ERROR',
'FATAL', 'FileHandler', 'Filter', 'Filterer', 'Formatter', 'Handler',
'INFO', 'LogRecord', 'Logger', 'LoggerAdapter', 'Manager', 'NOTSET',
'NullHandler', 'PlaceHolder', 'RootLogger', 'StreamHandler', 'WARN',
'WARNING', '__all__', '__author__', '__builtins__', '__date__',
'__doc__', '__file__', '__name__', '__package__', '__path__',
'__status__', '__version__', '_acquireLock', '_addHandlerRef',
'_checkLevel', '_defaultFormatter', '_handlerList', '_handlers',
'_levelNames', '_lock', '_loggerClass', '_releaseLock',
'_removeHandlerRef', '_showwarning', '_srcfile', '_startTime',
'_unicode', '_warnings_showwarning', 'addLevelName', 'atexit',
'basicConfig', 'cStringIO', 'captureWarnings', 'codecs', 'critical',
'currentframe', 'debug', 'disable', 'error', 'exception', 'fatal',
'getLevelName', 'getLogger', 'getLoggerClass', 'info', 'log',
'logMultiprocessing', 'logProcesses', 'logThreads', 'makeLogRecord',
'os', 'raiseExceptions', 'root', 'setLoggerClass', 'shutdown', 'sys',
'thread', 'threading', 'time', 'traceback', 'warn', 'warning',
'warnings', 'weakref']
这篇关于与文件同名的导入模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文