cbor2
cbor2 copied to clipboard
Add cbor2.tool option to generate bytes from python literal
I use cbor2 to parse and generate test sequences for my application. When developing, it is sometimes useful to create one-off cbor sequences to test an application. Therefore, it would be great if the cbor2.tool was extended to convert python literals to cbor data.
Here is a potential example of how it could be implemented:
from cbor2 import dumps
import ast
import sys
# parses a string as a python literal, and then converts to cbor and prints the bytes
def dumps_literal(literal):
cbor_val = ast.literal_eval(literal)
sys.stdout.buffer.write(dumps(cbor_val))
if __name__ == "__main__":
dumps_literal(sys.argv[1])
# Example output:
#
# $ python3 -m write_cbor '{"Hello" : ["w", "o", "r", "l","d"]}' | xxd -p
# a16548656c6c6f856177616f6172616c6164
#
# $ python3 -m write_cbor '("abc", 1,2,3)' | xxd -p
# 8463616263010203
Thoughts?
Yes this is a useful idea thank you!
In addition to parsing a string from the command line it might be good to accept a python or json string from stdin.
I would accept a pull request or work on it later when I have time.