简体   繁体   English

转义的字节字符串到字节字符串

[英]Escaped string of bytes to bytestring

I'm new to Python and I need to read bytestring from a command line argument. 我是Python的新手,我需要从命令行参数读取字节串。 I'm using Python 3.4. 我正在使用Python 3.4。

At the moment, I'm using argparse to parse the arguments, with this configuration for the data: parser.add_argument("-d", "--data", default=b'\\0') 此刻,我正在使用argparse来解析参数,并使用以下数据配置: parser.add_argument("-d", "--data", default=b'\\0')

When I call my program with -d argument (eg python myprogram.py -d b'd\\x00!\\x00W\\x00' ), it interprets the value of -d as a string, escaping slashes and treating the 'b' as part of the string, like this: 'b\\\\'d\\\\x00!\\\\x00W\\\\x00\\\\'' 当我使用-d参数调用程序时(例如python myprogram.py -d b'd\\x00!\\x00W\\x00' ),它将-d的值解释为字符串,转义斜线并将'b'视为字符串的一部分,例如: 'b\\\\'d\\\\x00!\\\\x00W\\\\x00\\\\''

Is there a way to unescape the output from argparse and convert it to bytes? 有没有一种方法可以取消argparse的输出并将其转换为字节?

You'd normally have the shell formulate the exact bytes, but since you cannot pass in NUL bytes as arguments asking users to pass in escape sequences is a reasonable work-around. 通常,您可以让Shell制定出确切的字节,但是由于您无法传递NUL字节,因为要求用户传递转义序列的参数是一种合理的解决方法。

However, the shell is not going to interpret Python byte string literal notation. 但是,shell不会解释Python字节字符串文字表示法。

In this case, I'd ask the user to enter hexadecimal values instead: 在这种情况下,我会要求用户输入十六进制值:

python myprogram.py -d "64 00 21 00 57 00"

and use the binascii.unhexlify() function to produce your bytes value from that (removing any whitespace first): 并使用binascii.unhexlify()函数从中产生bytes值(首先删除任何空白):

whitespace = dict.fromkeys((9, 10, 13, 32))  # tab, space, newline and carriage return
data = binascii.unhexlify(args.data.translate(whitespace))

This does require that you set your default argument value to a compatible value: 这确实需要将默认参数值设置为兼容值:

parser.add_argument("-d", "--data", default='00')

The alternative would be to use the ast.literal_eval() function to interpret the Python byte string literal syntax: 另一种方法是使用ast.literal_eval()函数来解释Python字节字符串的文字语法:

data = ast.literal_eval(args.data)

and your default'd be: 而您的默认设置为:

parser.add_argument("-d", "--data", default=repr(b'\0'))

but take into account that this function accepts any Python literal, so you could end up with any other object type, including numbers, strings and containers. 但要考虑到此函数接受任何Python文字,因此您可能会遇到任何其他对象类型,包括数字,字符串和容器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM