导入模块与文件

时间:2015-11-30 14:13:00

标签: python import importerror

我想将日志记录https://docs.python.org/3/library/logging.html导入名为logging.py的文档中。当我尝试导入logging.handlers时,它失败了,因为我相信它正在搜索文档中的处理程序函数,而不是从模块导入。我该如何解决这个问题,以便查找更高级别的日志记录而不是查看文件?

2 个答案:

答案 0 :(得分:1)

您可以通过从python路径中删除当前目录(首先在sys.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']

答案 1 :(得分:0)

如果您使用的名称与标准库名称相同,则可以使用distutils.sysconfig.get_python_lib首先在路径中插入标准的lib packages目录以找到目录,这仍然可以让您使用任何包在您的脚本目录中:

import sys
import distutils.sysconfig as sysconfig
sys.path.insert(0, sysconfig.get_python_lib(standard_lib=1))

import logging
print(logging.__file__)

输出:

$ python3 logging.py 
/usr/lib/python3.4/logging/__init__.py
$ python logging.py 
/usr/lib/python2.7/logging/__init__.pyc

如果要将路径设置恢复正​​常,可以弹出并导入仍然有效:

import sys
import distutils.sysconfig as sysconfig
sys.path.insert(0, sysconfig.get_python_lib(standard_lib=1))
print(sys.path)
import logging
sys.path.pop(0)
print("")
print(logging.__file__)
print("")
print(sys.path)

输出:

$ python3 logging.py 
['/usr/lib/python3.4', '/home/padraic', '/home/padraic/mymods', '/usr/lib/python3.4', '/usr/lib/python3.4/plat-x86_64-linux-gnu', '/usr/lib/python3.4/lib-dynload', '/home/padraic/.local/lib/python3.4/site-packages', '/usr/local/lib/python3.4/dist-packages', '/usr/lib/python3/dist-packages', '/usr/lib/python3.4/dist-packages']

/usr/lib/python3.4/logging/__init__.py

['/home/padraic', '/home/padraic/mymods', '/usr/lib/python3.4', '/usr/lib/python3.4/plat-x86_64-linux-gnu', '/usr/lib/python3.4/lib-dynload', '/home/padraic/.local/lib/python3.4/site-packages', '/usr/local/lib/python3.4/dist-packages', '/usr/lib/python3/dist-packages', '/usr/lib/python3.4/dist-packages']