如何在代码中找到非ASCII字节?
在我制作App Engine应用的时候,突然遇到了一个错误,这个错误每隔几次请求就会出现一次:
run_wsgi_app(application)
File "/home/ubuntu/Programs/google/google_appengine/google/appengine/ext/webapp/util.py", line 98, in run_wsgi_app
run_bare_wsgi_app(add_wsgi_middleware(application))
File "/home/ubuntu/Programs/google/google_appengine/google/appengine/ext/webapp/util.py", line 118, in run_bare_wsgi_app
for data in result:
File "/home/ubuntu/Programs/google/google_appengine/google/appengine/ext/appstats/recording.py", line 897, in appstats_wsgi_wrapper
result = app(environ, appstats_start_response)
File "/home/ubuntu/Programs/google/google_appengine/google/appengine/ext/webapp/_webapp25.py", line 717, in __call__
handler.handle_exception(e, self.__debug)
File "/home/ubuntu/Programs/google/google_appengine/google/appengine/ext/webapp/_webapp25.py", line 463, in handle_exception
self.error(500)
File "/home/ubuntu/Programs/google/google_appengine/google/appengine/ext/webapp/_webapp25.py", line 436, in error
self.response.clear()
File "/home/ubuntu/Programs/google/google_appengine/google/appengine/ext/webapp/_webapp25.py", line 288, in clear
self.out.seek(0)
File "/usr/lib/python2.7/StringIO.py", line 106, in seek
self.buf += ''.join(self.buflist)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd7 in position 208: ordinal not in range(128)
我真的不知道这个问题出在哪里,它只在我使用一个特定的函数时发生,但我无法追踪到我所有的字符串。
这个字节可能是像' " [ ]
这样的字符,只不过是用另一种语言表示的。
我该如何找到这个字节,可能还有其他的字节呢?
我在ubuntu 11.04上运行的是python 2.7的GAE。
谢谢。
*更新*
这是我最终使用的代码: from codecs import BOM_UTF8 from os import listdir, path p = "path"
def loopPath(p, times=0):
for fname in listdir(p):
filePath = path.join(p, fname)
if path.isdir(filePath):
return loopPath(filePath, times+1)
if fname.split('.', 1)[1] != 'py': continue
f = open(filePath, 'r')
ln = 0
for line in f:
#print line[:3] == BOM_UTF8
if not ln and line[:3] == BOM_UTF8:
line = line[4:]
col = 0
for c in list(line):
if ord(c) > 128:
raise Exception('Found "'+line[c]+'" line %d column %d in %s' % (ln+1, col, filePath))
col += 1
ln += 1
f.close()
loopPath(p)
5 个回答
这段代码 应该 列出出错的行:
grep -v [:alnum:] dodgy_file
$ cat test
/home/ubuntu/tmp/SO/c.awk
$ cat test2
/home/ubuntu/tmp/SO/c.awk
な
$ grep -v [:alnum:] test
$ grep -v [:alnum:] test2
な
我在把UTF-8文件转换成latin1 LaTeX的时候,也遇到了类似的问题。我想要一个我文件中所有“恶心”的unicode字符的列表。
可能你需要的东西还更多,但我用的是这个:
UNICODE_ERRORS = {}
def fortex(exc):
import unicodedata, exceptions
global UNICODE_ERRORS
if not isinstance(exc, exceptions.UnicodeEncodeError):
raise TypeError("don't know how to handle %r" % exc)
l = []
print >>sys.stderr, " UNICODE:", repr(exc.object[max(0,exc.start-20):exc.end+20])
for c in exc.object[exc.start:exc.end]:
uname = unicodedata.name(c, u"0x%x" % ord(c))
l.append(uname)
key = repr(c)
if not UNICODE_ERRORS.has_key(key): UNICODE_ERRORS[key] = [ 1, uname ]
else: UNICODE_ERRORS[key][0] += 1
return (u"\\gpTastatur{%s}" % u", ".join(l), exc.end)
def main():
codecs.register_error("fortex", fortex)
...
fileout = codecs.open(filepath, 'w', DEFAULT_CHARSET, 'fortex')
...
print UNICODE_ERROS
这有帮助吗?
下面是Python文档中相关的摘录:
codecs.register_error(name, error_handler) 这个函数用来注册一个错误处理函数,叫做error_handler,注册时给它一个名字name。如果在编码或解码过程中出现错误,就会调用这个error_handler,前提是你在错误参数中指定了name。
在编码时,error_handler会接收到一个UnicodeEncodeError实例,这个实例包含了错误发生位置的信息。错误处理函数必须要么抛出这个错误,或者抛出其他的异常,要么返回一个元组,其中包含一个可以替代无法编码部分的内容,以及一个继续编码的位置。编码器会用这个替代内容进行编码,然后从指定的位置继续编码原始输入。如果返回的位置超出了范围,就会抛出一个IndexError错误。
这段话的意思是,它会逐个检查每一行代码中的每一个字符。可以想象成这样:
# -*- coding: utf-8 -*-
import sys
data = open(sys.argv[1])
line = 0
for l in data:
line += 1
char = 0
for s in list(unicode(l,'utf-8')):
char += 1
try:
s.encode('ascii')
except:
print 'Non ASCII character at line:%s char:%s' % (line,char)