ealeon
ealeon

Reputation: 12462

Converting \x00 with a space

Im reading a /proc//cmdline file via:

pfile = '/proc/%s/cmdline' % pid
if os.path.isfile(pfile):
    fh = open(pfile, 'r')
    pname = repr(fh.read())
    fh.close()

print pname

OUTPUT:

'myexe\x00arg\x00arg2'

if i remove repr, there is no space between the words

'myexeargarg2'

So i changed it to

' '.join(fh.read().split('\x00'))

Then, I got:

'myexe arg arg2'

Just wondering if there are other ways to convert \x00 into a space?

Upvotes: 0

Views: 1839

Answers (3)

Pieter
Pieter

Reputation: 2162

For python3 needs the "b" binary prefix for replace.

content = b'cmd\x00arg1\x00arg2\x00'
print(content.replace(b"\x00", b" "))

Result: b'cmd arg1 arg2 '

Upvotes: 0

shuttle87
shuttle87

Reputation: 15934

If you look up an ASCII table you will see that \x00 is the NULL character. When you print something str is called on it which attempts to create a printable version of the data and unprintable characters don't get printed. You can see which characters are printable by looking at string.printable:

import string
if '\x00' in string.printable:
    print "printable"
else:
    print "unprintable"

When you run this you will see this outputs "unprintable".

However repr makes an attempt to generate something that can recreate the original data so the \x00 needs to be visible there because that's needed to recreate the original data.

If you want to get spaces wherever you had \x00 all you need to do is to replace it with a space with fh.replace('\x00', ' ').

Upvotes: 3

Souss
Souss

Reputation: 36

Here a short example that will help you to answer your Question.

content = b'cmd\x00arg1\x00arg2\x00'
print(content.replace("\x00", " "))

It will replace the occurences as explain here.

Upvotes: 2

Related Questions