Skip to content

Add cbor2.tool option to generate bytes from python literal #103

Description

@apgoetz

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?

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions