我希望我的 Python 脚本能够在 Windows 中读取 Unicode 命令行参数。但似乎 sys.argv 是以某种本地编码而不是 Unicode 编码的字符串。如何阅读完整的 Unicode 命令行?
示例代码:argv.py
import sys
first_arg = sys.argv[1]
print first_arg
print type(first_arg)
print first_arg.encode("hex")
print open(first_arg)
在为日语代码页设置的 PC 上,我得到:
C:\temp>argv.py "PC・ソフト申請書08.09.24.doc"
PC・ソフト申請書08.09.24.doc
<type 'str'>
50438145835c83748367905c90bf8f9130382e30392e32342e646f63
<open file 'PC・ソフト申請書08.09.24.doc', mode 'r' at 0x00917D90>
我相信这是 Shift-JIS 编码的,它对那个文件名“有效”。但它会中断带有不在 Shift-JIS 字符集中的字符的文件名——最终的“打开”调用失败:
C:\temp>argv.py Jörgen.txt
Jorgen.txt
<type 'str'>
4a6f7267656e2e747874
Traceback (most recent call last):
File "C:\temp\argv.py", line 7,
in <module>
print open(first_arg)
IOError: [Errno 2] No such file or directory: 'Jorgen.txt'
注意——我说的是 Python 2.x,而不是 Python 3.0。我发现 Python 3.0 提供sys.argv
了正确的 Unicode。但是现在过渡到 Python 3.0 还为时过早(由于缺乏 3rd 方库支持)。
更新:
一些答案说我应该根据sys.argv
编码的任何内容进行解码。问题在于它不是完整的 Unicode,因此某些字符无法表示。
这是让我感到悲伤的用例:我在 Windows Explorer 中启用了将文件拖放到 .py 文件上。我的文件名包含各种字符,包括一些不在系统默认代码页中的字符。当字符在当前代码页编码中不可表示时,我的 Python 脚本在所有情况下都无法通过 sys.argv 获得正确的 Unicode 文件名。
当然有一些 Windows API 可以读取带有完整 Unicode 的命令行(Python 3.0 可以做到)。我假设 Python 2.x 解释器没有使用它。