在python3中将命令行参数作为字节访问

时间:2014-10-22 09:01:31

标签: python-3.x binary-data argv

是否可以访问原始argv元素二进制内容?

$ python3 -c'import sys;print(sys.argv);' `echo -ne "\xff\x80\x00\xff"`
['-c', '\udcff\udc80\udcff']

1 个答案:

答案 0 :(得分:1)

您可以按如下方式获取argv字符:

#!/usr/bin/python3
import sys
arg1_bytes = sys.argv[1].encode(sys.getfilesystemencoding(), 'surrogateescape')

来源:PEP 383 - Non-decodable Bytes in System Character Interfaces,来自answer on "Command-line arguments as bytes instead of strings in python3";另见answer on "sys.argv as bytes in Python 3k"