str()在函数的自定义 error_handler 中引用(或更改)使用 codecs.register_error() 设置的全局变量是坏/可疑/允许的做法吗?
我正在尝试实现一个自定义的“backslashreplace”函数,除了反斜杠转义之外,还将结果括在单引号(')或双引号(“)中,非常类似于 gnu 程序ls在--quoting-style=shell-escape.
问题是,单引号或双引号之间的选择无法传输到错误处理程序。让它知道使用哪个的唯一方法是引用一个全局变量,该变量标记是否应该使用单/双引号。
(我使用的是Python版本3.6.9)。
这是一个示例程序:
#!/usr/bin/env python3
import codecs
# in my program, quote varies between these two at runtime
#quote = "'"
quote = '"'
def my_replace( e ):
global quote # <-- global variable
if not isinstance( e, UnicodeDecodeError ):
raise TypeError( "don't know how to handle %r" % e )
x = []
for c in e.object[e.start:e.end]:
try:
if c == 0x93 or c == 0x94:
x.append( quote + ( "$'\\%o'" % c) + quote )
except KeyError:
return( None )
return( "".join(x), e.end )
codecs.register_error( "my_replace", my_replace )
s = b'61. \x93Gleich wie ein Hirsch begehret\x94, P.169_ IV. Variatio 3.flac'
s = str( s, 'utf-8', errors='my_replace' )
print( quote + s + quote )
江户川乱折腾
三国纷争
随时随地看视频慕课网APP
相关分类