Python - sys.argv特殊符号(€,¢,₪等...)

时间:2016-01-15 23:49:24

标签: python input unicode parameters

我必须在我的python文件的输入参数上使用货币符号。好吧,但我不知道,如何将其转换为可用的方式。

示例:

我的意见:

--amount 100.0 --input_currency € --output_currency CZK

我为€符号获得了什么:

\x80

我需要得到的东西:

u'\u20ac'

我尝试使用decode('utf-8')但它不起作用,它返回:

UnicodeDecodeError: 'utf8' codec can't decode byte 0x80 in position 0: invalid start byte

你能帮我吗?

2 个答案:

答案 0 :(得分:1)

在POSIX系统上,它完全取决于您的控制台或终端如何配置为这些字符串使用的编码。

在这些环境中,使用locale.getpreferredencoding()查询配置的编码,然后使用它来解码字符串。这不是万无一失的,但只要控制台或终端配置正确,它就应该有用。

在您的特定情况下,您可能正在使用配置为使用Windows Codepage 1252的Windows系统:

>>> '\x80'.decode('cp1252')
u'\u20ac'
>>> print '\x80'.decode('cp1252')
€

Windows确实提供了GetCommandLineW()CommandLineToArgvW()函数来检索命令行的 Unicode 值,然后将该值解析为argv - 就像阵列;使用Python中的这个可以使用ctypes library;释义this example这就是你如何使用它:

from ctypes import WINFUNCTYPE, windll, POINTER, byref, c_int
from ctypes.wintypes import LPWSTR, LPCWSTR
GetCommandLineW = WINFUNCTYPE(LPWSTR)(("GetCommandLineW", windll.kernel32))
CommandLineToArgvW = WINFUNCTYPE(POINTER(LPWSTR), LPCWSTR, POINTER(c_int))(("CommandLineToArgvW", windll.shell32))

argc = c_int(0)
argv_unicode = CommandLineToArgvW(GetCommandLineW(), byref(argc))

答案 1 :(得分:0)

在Python 3上,sys.argv已经是Unicode字符串列表。你不需要做任何事情。

在Python 2上,在Windows上,你应该use Unicode API (CommandLineToArgvW(), GetCommandLineW())。它允许传递无法使用当前OEM代码页表示的字符,例如cp437(chcp result)。

在Python 2上,在POSIX上,sys.argv[i]可以是任意字节序列。通常,它可以使用从Linux上的语言环境派生的sys.getfilesystemencoding()进行编码。

请参阅Best way to decode command line inputs to Unicode Python 2.7 scripts