【问题标题】:How to input Polish characters into CMD as a Python parameter? [duplicate]如何将波兰语字符作为 Python 参数输入 CMD? [复制]
【发布时间】:2016-09-29 11:47:50
【问题描述】:

我刚开始学习 Python 编码,我有一个简单的 Python 程序,它返回 Cześć <input>,其中 <input> 是用户可以输入到 CMD 作为此 Python 程序参数的名称。如果没有输入,它将返回Cześć Świat。它工作正常,但是当我输入名称Łukasz 时,它会从Ł 中删除罢工,程序返回Cześć Lukasz 而不是正确的Cześć Łukasz

在 Windows CMD 中,我使用 CD 命令转到包含 Python 程序的文件夹,然后使用以下语句执行 Python 程序:hello.py Łukasz

我的脚本看起来像这样(它最初来自 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-8cp1252 会导致波兰字母(例如ĄĆĆĘŁŃŚŻŹ)的重音被去除,除了字母Óó 在使用cp1252 时似乎保留了它们的重音,因为使用该字母与utf-8 导致了前面提到的异常。

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

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

【问题讨论】:

    标签: python python-2.7 cmd diacritics


    【解决方案1】:

    This is a known limitation of Python 2 in Windowssys.argv 不接受 Unicode,字符被截断为标准 ANSI 字符页。升级到 Python 3 将解决您的问题。

    【讨论】:

    • 哇... Python 3 甚至不再需要u'some string' 和解码/编码,它只是接受我正在使用变音符号!谢谢你:)
    猜你喜欢
    • 2013-10-10
    • 2013-04-20
    • 2014-10-03
    • 2020-02-17
    • 1970-01-01
    • 2018-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多