12

根据文档,在 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 的输出。我在使用“本机”python 2.7.3 的 Ubuntu 机器上遇到了完全相同的错误。

4

3 回答 3

12

该代码将两个实例shlex.split()都包装在一个对象中unicode(),该对象只能处理 Latin-1 字节(因此不是完整的 unicode 代码点范围)。str()StringIO()

如果您仍想使用,则必须进行编码(UTF-8 应该可以)shlex.split();该模块的维护者意味着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']

一个现已关闭的 Python 问题试图解决这个问题,但该模块非常面向字节流,并且没有实现新的补丁。现在使用iso-8859-1UTF-8编码是我能为你想出的最好的方法。

于 2013-01-08T16:07:20.940 回答
3

实际上已经有五年多的补丁了。去年我厌倦了在每个项目中复制一个 ushlex 并将其放在 PyPI 上:

https://pypi.python.org/pypi/ushlex/

于 2014-05-13T09:02:27.037 回答
0

我用的是 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']
于 2019-06-25T07:23:12.280 回答