1. python如何屏蔽控制台输出的红色字
把Foreground取消掉。
在PyCharm的设置中,运行窗口会把stderr的信息输出为红色。
Scrapy的默认设置是给rootlogger根据配置信息添加一个Handler,默认为handler=logging.StreamHandler()。所以我们的log信息都跑到stderr中去了。
2. 如何优雅的使用 python logging 模块
logging模块是可以通过配置文件来初始化,这样代码基本可以保持不动
有需求改配置文件就可以了
3. python中爬取得链接怎么控制台没有输出
Python编程中,往往需要将结果用print等输出,如果希望输出既可以显示到IDE的屏幕上,也能存到文件中(如txt)中,该怎么办呢?
方法1
可通过日志logging模块输出信息到文件或屏幕。但可能要设置log的level或输出端,对于同时需要记录debug error等信息的较为合适,官方教程推荐学习用更规范的logger来操作。
例如,可参考来自官网的这段代码。
import logging
logging.basicConfig(filename='log_examp.log',level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')
方法2
利用print输出两次
比如这里我想输出程序的path和程序的文件名
import os
# 第一句输出到consle:
print("filepath:",__file__,"\nfilename:",os.path.basename(__file__))
# 第二句输出到txt:
with open("outputlog.txt","a+") as f:
print("filepath:",__file__,
"\nfilename:",os.path.basename(__file__))
#当然 也可以用f.write("info")的方式写入文件
方法3
利用输出重定向输出两次
同样输出程序path和文件名
import os
import sys
temp=sys.stdout # 记录当前输出指向,默认是consle
with open("outputlog.txt","a+") as f:
sys.stdout=f # 输出指向txt文件
print("filepath:",__file__,
"\nfilename:",os.path.basename(__file__))
print("some other information")
print("some other")
print("information")
sys.stdout=temp # 输出重定向回consle
print(f.readlines()) # 将记录在文件中的结果输出到屏幕
R的重定向
这里多嘴补充一下,在windows下的R语言中,有个sink(‘文件名.后缀名’) 可以将输出重定向到文件中,然后用sink()重返控制台 很是方便
4. python用logging模块写日志文件无输出
来个简单点的
#-*-coding:utf-8-*-
importlogging
__author__='lpe234'
__date__='2015-04-30'
LOGGING_FILE='xx.log'
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s%(filename)s[line:%(lineno)d]%(levelname)s%(message)s',
filename=LOGGING_FILE,
filemode='a+'
)
logging.debug('debug')
logging.info('info')
logging.exception('exception')
logging.error('error')
logging.critical('critical')
5. 如何在Python中禁用并重新启用控制台日志记录
解决方案:
logger = logging.getLogger('my-logger')
logger.propagate = False
#now如果你使用logger它不会日志到控制台。
6. python程序中logging怎么用
简单将日志打印到屏幕:
[python] view plain
import logging
logging.debug('debug message')
logging.info('info message')
logging.warning('warning message')
logging.error('error message')
logging.critical('critical message')
输出:
WARNING:root:warning message
ERROR:root:error message
CRITICAL:root:critical message
可见,默认情况下Python的
logging模块将日志打印到了标准输出中,且只显示了大于等于WARNING级别的日志,这说明默认的日志级别设置为WARNING(日志级别等级
CRITICAL > ERROR > WARNING > INFO > DEBUG >
NOTSET),默认的日志格式为日志级别:Logger名称:用户输出消息。
灵活配置日志级别,日志格式,输出位置
[python] view plain
import logging
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S',
filename='/tmp/test.log',
filemode='w')
logging.debug('debug message')
logging.info('info message')
logging.warning('warning message')
logging.error('error message')
logging.critical('critical message')
查看输出:
cat /tmp/test.log
Mon, 05 May 2014 16:29:53 test_logging.py[line:9] DEBUG debug message
Mon, 05 May 2014 16:29:53 test_logging.py[line:10] INFO info message
Mon, 05 May 2014 16:29:53 test_logging.py[line:11] WARNING warning message
Mon, 05 May 2014 16:29:53 test_logging.py[line:12] ERROR error message
Mon, 05 May 2014 16:29:53 test_logging.py[line:13] CRITICAL critical message
可见在logging.basicConfig()函数中可通过具体参数来更改logging模块默认行为,可用参数有
filename:用指定的文件名创建FiledHandler(后边会具体讲解handler的概念),这样日志会被存储在指定的文件中。
filemode:文件打开方式,在指定了filename时使用这个参数,默认值为“a”还可指定为“w”。
format:指定handler使用的日志显示格式。
datefmt:指定日期时间格式。
level:设置rootlogger(后边会讲解具体概念)的日志级别
stream:用指定的stream创建StreamHandler。可以指定输出到sys.stderr,sys.stdout或者文件,默认为sys.stderr。若同时列出了filename和stream两个参数,则stream参数会被忽略。
format参数中可能用到的格式化串:
%(name)s Logger的名字
%(levelno)s 数字形式的日志级别
%(levelname)s 文本形式的日志级别
%(pathname)s 调用日志输出函数的模块的完整路径名,可能没有
%(filename)s 调用日志输出函数的模块的文件名
%(mole)s 调用日志输出函数的模块名
%(funcName)s 调用日志输出函数的函数名
%(lineno)d 调用日志输出函数的语句所在的代码行
%(created)f 当前时间,用UNIX标准的表示时间的浮 点数表示
%(relativeCreated)d 输出日志信息时的,自Logger创建以 来的毫秒数
%(asctime)s 字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒
%(thread)d 线程ID。可能没有
%(threadName)s 线程名。可能没有
%(process)d 进程ID。可能没有
%(message)s用户输出的消息
7. 如何打开python控制台
打开python控制台的方法:1、按下键盘上的【win+r】快捷键打开运行;2、在输入框中输入cmd,点击【确定】;3、在打开的命令提示符中执行python命令,这样就成功打开python控制台了。
具体方法:
(推荐教程:Python入门教程)
1、按下键盘上的【win+r】快捷键打开运行;
2、在输入框中输入cmd,点击【确定】;
3、在打开的命令提示符中执行python命令,这样就成功打开python控制台了。
8. python中使用logging模块在控制台打印日志的同时也打印log文件,但发现控制台的信息会出现重复打印
loggin模块需要进行很多封装才好用,你这种情况应该是初始化有问题,给你贴一段代码你自己照抄下来用用试试。
#-*-coding:UTF8-*-
#
importos
importlogging
classLogger(object):
'''
@summary:日志处理对象,对logging的封装
'''
def__init__(self,name='Logger'):
self.logger=logging.getLogger(name)
self.init_logger()
definit_logger(self):
self.logger.setLevel(logging.DEBUG)
#屏幕输出日志
stream=logging.StreamHandler()
stream.setLevel(logging.INFO)
#日志样式
fm_stream=logging.Formatter("[ 33[1;%(colorcode)sm%(levelname)s 33[0m%(asctime)s%(myfn)s:%(mylno)d:%(myfunc)s%(mymole)s]%(message)s","%m-%d%H:%M:%S")
stream.setFormatter(fm_stream)
self.logger.addHandler(stream)
defupdate_kwargs(self,kwargs,colorcode):
try:
fn,lno,func=self.logger.findCaller()
fn=os.path.basename(fn)
exceptExceptionasddd:
fn,lno,func="(unknownfile)",0,"(unknownfunction)"
ifnot"extra"inkwargs:
kwargs["extra"]={}
kwargs["extra"]["myfn"]=fn
kwargs["extra"]["mylno"]=lno
kwargs["extra"]["myfunc"]=func
kwargs["extra"]["colorcode"]=colorcode
kwargs["extra"]["mymole"]=""
defdebug(self,msg,*args,**kwargs):
self.update_kwargs(kwargs,"0")#原色
self.logger.debug(msg,*args,**kwargs)
definfo(self,msg,*args,**kwargs):
self.update_kwargs(kwargs,"32")#绿色
self.logger.info(msg,*args,**kwargs)
defwarning(self,msg,*args,**kwargs):
self.update_kwargs(kwargs,"33")#黄色
self.logger.warning(msg,*args,**kwargs)
deferror(self,msg,*args,**kwargs):
self.update_kwargs(kwargs,"31")#红色
self.logger.error(msg,*args,**kwargs)
defcritical(self,msg,*args,**kwargs):
self.update_kwargs(kwargs,"31")#红色
self.logger.critical(msg,*args,**kwargs)
使用方法:
fromloggerimportLogger
Logger().info('xxxxx')
Logger().warning('xxxxx')
Logger().error('xxxxx')
9. 怎么用logging调试python程序
Logging模块构成
组成
主要分为四个部分:
Loggers:提供应用程序直接使用的接口
Handlers:将Loggers产生的日志传到指定位置
Filters:对输出日志进行过滤
Formatters:控制输出格式
模块使用示例
简单例子
打印输出
In [5]: import logging
In [6]: logging.warning("FBI warning")
WARNING:root:FBI warning
In [7]: logging.info("information")
# 没有打印是因为默认级别是warning
10. python logging 问题
请参考我下面的代码以及对应的 log,看上去没有问题,我怀疑是 log config 的问题
importlogging
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s%(filename)s[line:%(lineno)d]%(message)s',
datefmt='%a,%d%b%Y%H:%M:%S',
filename='log.log',
filemode='w')
classA:
def__init__(self):
logging.info('A')
__c=C()
__d=D()
classB:
def__init__(self):
logging.info('B')
classC:
def__init__(self):
logging.info('C')
__e=E()
__f=F()
classD:
def__init__(self):
logging.info('D')
classE:
def__init__(self):
logging.info('E')
classF:
def__init__(self):
logging.info('F')
if__name__=='__main__':
a=A()
b=B()