如何将波兰字符作为Python参数输入到CMD中?

2024-09-29 03:35:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚开始学习用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-8sys.argv[1]进行解码,但不知怎么的,当我使用字母Óó时,它会抛出一个难看的异常(请参见this SO answer)。使用utf-8cp1252都会导致波兰字母(例如,ĄĆĘŁŃŚŹ)的重音符号,但字母Óó在使用cp1252时似乎保持了重音,因为使用utf-8会导致前面提到的异常。在

所以我的问题是,如何从CMD中检索完整的字符串并在Python程序中使用?在

我不会接受建议删除/忽略口音的答案!


Tags: thename程序名称cmdinputmainsys