Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python3 print raw byte

I want a simple, one-liner solution that will print a byte.

python3 -c 'print("A", end="")' | xxd -p
python3 -c 'print("\x41", end="")' | xxd -p

The output from both lines is 41, as expected

python3 -c 'print("\xec", end="")' | xxd -p

This outputs: c3ac

I think this has something to do with the fact that python3 uses utf-8 as default encoding, however I couldn't find a simple solution for this.

Basically, I want the python3 equivalent of:

perl -e 'print "\xec"'
like image 953
Timo89 Avatar asked Jan 05 '23 13:01

Timo89


1 Answers

Strings printed are written to the sys.stdout object and encoded to your system encoding. What bytes are actually written depends on your system locale; your terminal is configured for UTF-8, so the U+00EC character is encoded to two bytes.

You need to write raw bytes to sys.stdout.buffer instead:

python3 -c 'import sys; sys.stdout.buffer.write(b"\xec")'

Note the b prefix.

Demo:

$ python3 -c 'import sys; sys.stdout.buffer.write(b"\xec")' | xxd -p
ec
like image 162
Martijn Pieters Avatar answered Jan 14 '23 02:01

Martijn Pieters