Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
apgoetz opened this issue Dec 30, 2020 · 1 comment
Open

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

apgoetz opened this issue Dec 30, 2020 · 1 comment

Comments

@apgoetz
Copy link

apgoetz commented Dec 30, 2020

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?

@Sekenre
Copy link
Collaborator

Sekenre commented Feb 18, 2021

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants