1

I've been trying to use the linux shell to output a sequence of bytes into a file using Python. The problem is when I do:

python -c "print '\x11\x22\x33\x44'" > new_file

The new_file contains '\x11\x22\x33\x44\x0a'.

I looked up similar questions here on StackOverflow and tried to strip out the \x0a by the following and many other similar techniques:

python -c "print '\x11\x22\x33\x44'.rstrip('\x0a')" > new_file

The \x0a, however, refuses to go.

Has anyone run into this problem before? Would really appreciate a quick fix. Thanks.

PS: I've tried this with various versions of Python including 2.5, 2.7, 3.1, 3.3. All lead to the same problem.

user904832
  • 557
  • 1
  • 6
  • 10

1 Answers1

1

This is because the print function automatically adds a newline character at the end (ascii 0x0a). You can use the Python 3 version of print to set the end character:

> python3 -c "print('\x11\x22\x33\x44', end='')" > new_file
> hexdump -C new_file
11 22 33 44

If you really need to use Python 2, you can use this trick to run a multiline Python code in your terminal:

echo -e "import sys\nsys.stdout.write('\x11\x22\x33\x44')" | python > new_file
Community
  • 1
  • 1
julienc
  • 19,087
  • 17
  • 82
  • 82
  • 2
    or even fewer characters: `python -c "import sys; sys.stdout.write('\x11\x22\x33\x44')" > new_file` – bgporter Jun 20 '14 at 20:42
  • Thanks guys. This works perfectly. Just wondering though, why does 'print' a 0x0a but stdout.write doesn't? Is it because the print function assumes its arguments to be strings? – user904832 Jun 21 '14 at 09:24