相关疑难解决方法(0)

在Windows上的Python 2.x中从命令行参数中读取Unicode字符

我希望我的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)
Run Code Online (Sandbox Code Playgroud)

在我为日语代码页设置的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>
Run Code Online (Sandbox Code Playgroud)

这是我认为的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'
Run Code Online (Sandbox Code Playgroud)

注意 - 我在谈论Python 2.x,而不是Python 3.0.我发现Python 3.0提供sys.argv了正确的Unicode.但是转换到Python 3.0还有点早(由于缺乏第三方库支持).

更新:

一些答案说我应该根据sys.argv编码的内容进行解码.问题在于它不是完整的Unicode,因此某些字符不可表示.

这是让我感到悲伤的用例:我已经在Windows资源管理器中将文件拖放到.py文件中.我有各种字符的文件名,包括一些不在系统默认代码页中的字符.在所有情况下,当在当前代码页编码中无法表示字符时,我的Python脚本无法通过sys.argv获取正确的Unicode文件名.

肯定有一些Windows API用完整的Unicode读取命令行(而Python 3.0就是这样).我假设Python …

python windows unicode command-line python-2.x

29
推荐指数
2
解决办法
2万
查看次数

标签 统计

command-line ×1

python ×1

python-2.x ×1

unicode ×1

windows ×1