Python xlrd:禁止警告消息 [英] Python xlrd: suppress warning messages
问题描述
我使用 xlrd
处理 Excel 文件.我正在包含许多文件的文件夹上运行脚本,并且正在打印与这些文件相关的消息.但是,对于我运行的每个文件,我也会收到以下 xlrd 生成的错误消息:
I am using xlrd
to process Excel files. I am running a script on a folder that contains many files, and I am printing messages related to the files. However, for each file I run, I get the following xlrd-generated error message as well:
WARNING *** OLE2 inconsistency: SSCS size is 0 but SSAT size is non-zero
有没有办法抑制这个错误信息,让 CLI 只打印我想要的信息?
Is there a way to suppress this error message, so the CLI will only print the message I want it to?
推荐答案
查看xlrd 文档.open_workbook
函数的第二个参数是 logfile
,它应该是一个打开的文件对象或类似行为.它只需要支持一个 write
方法.默认为 sys.stdout
.
Check out the relevant part of the xlrd docs. The 2nd arg of the open_workbook
function is logfile
which should be an open file object or act-alike. All it needs to support is a write
method. It defaults to sys.stdout
.
所以,像这样(未经测试)应该可以完成这项工作:
So, something like this (untested) should do the job:
class MyFilter(object):
def __init__(self, mylogfile=sys.stdout):
self.f = mylogfile
def write(self, data):
if "WARNING *** OLE2 inconsistency" not in data:
self.f.write(data)
#start up
log = open("the_log_file.txt", "w")
log_filter = MyFilter(log)
book = xlrd.open_workbook("foo.xls", logfile=log_filter)
# shut down
log.close()
# or use a "with" statement
更新以回应@DaniloBargen的回答:
Update in response to answer by @DaniloBargen:
不是 xlrd
单独编写换行符,而是 Python print
语句/函数.这个脚本:
It's not xlrd
that's writing the newline separately, it's the Python print
statement/function. This script:
class FakeFile(object):
def write(self, data):
print repr(data)
ff = FakeFile()
for x in "foo bar baz".split():
print >> ff, x
为所有 Python 2.2 到 2.7 生成此输出:
produces this output for all Pythons 2.2 to 2.7 both inclusive:
'foo'
'\n'
'bar'
'\n'
'baz'
'\n'
适当现代化的脚本(作为函数而不是语句打印)为 2.6、2.7、3.1、3.2 和 3.3 生成相同的输出.您可以使用更复杂的过滤器类来解决此问题.以下示例还允许检查一系列短语:
A suitably modernised script (print as a function instead of a statement) produces identical output for 2.6, 2.7, 3.1, 3.2, and 3.3. You can work around this with a more complicated filter class. The following example additionally allows a sequence of phrases to be checked for:
import sys, glob, xlrd
class MyFilter(object):
def __init__(self, mylogfile=sys.stdout, skip_list=()):
self.f = mylogfile
self.state = 0
self.skip_list = skip_list
def write(self, data):
if self.state == 0:
found = any(x in data for x in self.skip_list)
if not found:
self.f.write(data)
return
if data[-1] != '\n':
self.state = 1
else:
if data != '\n':
self.f.write(data)
self.state = 0
logf = open("the_log_file.txt", "w")
skip_these = (
"WARNING *** OLE2 inconsistency",
)
try:
log_filter = MyFilter(logf, skip_these)
for fname in glob.glob(sys.argv[1]):
logf.write("=== %s ===\n" % fname)
book = xlrd.open_workbook(fname, logfile=log_filter)
finally:
logf.close()
这篇关于Python xlrd:禁止警告消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!