Подтвердить что ты не робот

Не пытайтесь прочитать unicode из командной строки?

Запуск Python 2.7

При выполнении:

$ python client.py get_emails -a "åäö"

Я получаю:

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'

Это мой парсер:

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

Означает ли это, что я не могу использовать символы юникода с модулем python argparse?

4b9b3361

Ответ 1

Вы можете попробовать

type=lambda s: unicode(s, 'utf8')

вместо

type=unicode

Без аргумента кодировки unicode() по умолчанию соответствует ascii.

Ответ 2

Аргументы командной строки кодируются с помощью 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)

Примечание. Это не нужно в Python 3 (аргументы уже Unicode). В этом случае он использует os.fsdecode(), потому что иногда аргументы командной строки могут быть недопустимы. См. PEP 383 - Non-decodable Bytes в интерфейсах системных символов.