我刚开始学习用Python编写代码,我有一个简单的Python程序,它返回Cześć <input>
,其中<input>
是用户可以输入到CMD中作为Python程序参数的名称。如果没有输入,它将返回Cześć Świat
。它工作得很好,但是当我输入名称Łukasz
时,它会从Ł
中去掉删除符,程序返回Cześć Lukasz
,而不是正确的Cześć Łukasz
。在
在windowscmd中,我使用CD命令转到包含Python程序的文件夹,在那里我使用语句:hello.py Łukasz
来执行Python程序。在
我的脚本如下所示(它最初来自于Google的Python练习(source),我对其进行了编辑,使其适用于Python版本2.7中的unicode字符,并将“hello”替换为“cześć”):
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
# Define a main() function that prints a little greeting.
def main():
# Get the name from the command line, using 'World' as a fallback.
if len(sys.argv) >= 2:
name = sys.argv[1].decode('cp1252')
else:
name = u'Świat'
str = u'Cześć '+name
print str.encode('utf-8')
# This is the standard boilerplate that calls the main() function.
if __name__ == '__main__':
main()
最初我用utf-8
对sys.argv[1]
进行解码,但不知怎么的,当我使用字母Óó
时,它会抛出一个难看的异常(请参见this SO answer)。使用utf-8
或cp1252
都会导致波兰字母(例如,ĄĆĘŁŃŚŹ)的重音符号,但字母Óó
在使用cp1252
时似乎保持了重音,因为使用utf-8
会导致前面提到的异常。在
所以我的问题是,如何从CMD中检索完整的字符串并在Python程序中使用?在
我不会接受建议删除/忽略口音的答案!
This is a known limitation of Python 2 in Windows。
sys.argv
不接受Unicode,字符被截断为标准ANSI字符页。升级到python3将解决您的问题。在相关问题 更多 >
编程相关推荐