根据文档,在Python 2.7.3中,shlex应该支持UNICODE。但是,当运行下面的代码时,我得到:UnicodeEncodeError: 'ascii' codec can't encode characters in position 184-189: ordinal not in range(128)
我做错了什么吗?
import shlex
command_full = u'software.py -fileA="sequence.fasta" -fileB="新建文本文档.fasta.txt" -output_dir="..." -FORMtitle="tst"'
shlex.split(command_full)确切的错误如下:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shlex.py", line 275, in split
lex = shlex(s, posix=posix)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shlex.py", line 25, in __init__
instream = StringIO(instream)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 44-49: ordinal not in range(128)这是我的mac在macports中使用python的输出。我在Ubuntu机器上用“本地”python 2.7.3得到了完全相同的错误。
发布于 2013-01-09 00:07:21
shlex.split()代码将unicode()和str()实例包装在一个StringIO()对象中,该对象只能处理拉丁-1字节(因此不能处理整个Unicode码点范围)。
如果您仍然想使用shlex.split(),就必须进行编码(应该可以使用UTF-8 );模块的维护者意味着现在支持unicode()对象,只是不支持拉丁语-1范围之外的任何代码点。
编码、拆分、解码给了我:
>>> map(lambda s: s.decode('UTF8'), shlex.split(command_full.encode('utf8')))
[u'software.py', u'-fileA=sequence.fasta', u'-fileB=\u65b0\u5efa\u6587\u672c\u6587\u6863.fasta.txt', u'-output_dir=...', u'-FORMtitle=tst']一个now closed Python issue试图解决这个问题,但是这个模块是非常面向字节流的,并且没有新的补丁出现。目前,使用iso-8859-1或UTF-8编码是我能想到的最好的方法。
发布于 2014-05-13 17:02:27
实际上,有一个补丁已经超过五年了。去年,我厌倦了在每个项目中复制一个ushlex,并将其放到PyPI上:
发布于 2019-06-25 15:23:12
我使用Python 2.7.16,我发现
shlex可以使用通用字符串'xxxx‘
ushlex可以与u“‘xxx”一起工作
# -*- coding:utf8 -*-
import ushlex
import shlex
command_full1 = 'software.py -fileA="sequence.fasta" -fileB="新建文本文档.fasta.txt" -output_dir="..." -FORMtitle="tst"'
print shlex.split(command_full1)
command_full2 = u'software.py -fileA="sequence.fasta" -fileB="新建文本文档.fasta.txt" - output_dir="..." -FORMtitle="tst"'
print ushlex.split(command_full2)输出:
['software.py', '-fileA=sequence.fasta', '-fileB=\xe6\x96\xb0\xe5\xbb\xba\xe6\x96\x87\xe6\x9c\xac\xe6\x96\x87\xe6\xa1\xa3.fasta.txt', '-output_dir=...', '-FORMtitle=tst']
[u'software.py', u'-fileA=sequence.fasta', u'-fileB=\u65b0\u5efa\u6587\u672c\u6587\u6863.fasta.txt', u'-output_dir=...', u'-FORMtitle=tst']https://stackoverflow.com/questions/14218992
复制相似问题