不要从命令行中读取unicode吗?

Nic*_*son 12 python unicode argparse

运行Python 2.7

执行时:

$ python client.py get_emails -a "åäö"
Run Code Online (Sandbox Code Playgroud)

我明白了:

usage: client.py get_emails [-h] [-a AREA] [-t {rfc2822,plain}]
client.py get_emails: error: argument -a/--area: invalid unicode value: '\xc3\xa5\xc3\xa4\xc3\xb6'
Run Code Online (Sandbox Code Playgroud)

这是我的解析器:

def _argparse():
    desc = """
           Simple CLI-client for...
           """
    argparser = argparse.ArgumentParser(description=desc)
    subparsers = argparser.add_subparsers(dest='command')

    # create the parser for the "get_emails" command
    parser_get_emails = subparsers.add_parser('get_emails', help=u'Get email list')
    parser_get_emails.add_argument('-a', '--area', type=unicode, help='Limit to area')
    parser_get_emails.add_argument('-t', '--out_type', choices=['rfc2822', 'plain'],
                                   default='rfc2822', help='Type of output')

    args = argparser.parse_args()
    return args
Run Code Online (Sandbox Code Playgroud)

这是否意味着我不能在python argparse模块中使用任何unicode字符?

geo*_*org 17

你可以试试

type=lambda s: unicode(s, 'utf8')
Run Code Online (Sandbox Code Playgroud)

代替

type=unicode
Run Code Online (Sandbox Code Playgroud)

没有编码参数unicode()默认为ascii.

  • @NiclasNilsson:getdefaultlocale可以在环境下返回None,None,所以你需要一个后备,比如`getdefaultlocale()[1]或'utf8'` (2认同)
  • @georg:我没有看到你提供的链接中提到的`sys.getfilesystemencoding()`.为什么你认为`sys.argv`项不在`sys.getfilesystemencoding()`中?有不可解释的参数存在问题,但这是一个不同的问题. (2认同)

jfs*_*jfs 13

命令行参数使用sys.getfilesystemencoding()以下代码进行编码:

import sys

def commandline_arg(bytestring):
    unicode_string = bytestring.decode(sys.getfilesystemencoding())
    return unicode_string

# ...
parser_get_emails.add_argument('-a', '--area', type=commandline_arg)
Run Code Online (Sandbox Code Playgroud)

注意:您在Python 3中不需要它(参数已经是Unicode).它os.fsdecode()在这种情况下使用,因为有时命令行参数可能是不可解码的.请参阅PEP 383 - 系统字符接口中的不可解码字节.