简体   繁体   English

用空格转换\\ x00

[英]Converting \x00 with a space

Im reading a /proc//cmdline file via: 我通过以下方式读取/ proc // cmdline文件:

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

print pname

OUTPUT: OUTPUT:

'myexe\x00arg\x00arg2'

if i remove repr, there is no space between the words 如果我删除repr,则单词之间没有空格

'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? 只想知道是否还有其他方法可以将\\ x00转换为空格?

If you look up an ASCII table you will see that \\x00 is the NULL character. 如果您查找ASCII表,将会看到\\x00是NULL字符。 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. 当您打印内容时,会在其上调用str ,这会尝试创建数据的可打印版本,并且无法打印无法打印的字符。 You can see which characters are printable by looking at string.printable : 您可以通过查看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. 但是repr尝试生成可以重新创建原始数据的内容,因此\\x00必须在此处可见,因为重新创建原始数据是必需的。

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', ' ') . 如果要在\\x00位置获得空格,则只需用fh.replace('\\x00', ' ') replace空格fh.replace('\\x00', ' ')

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 . 它将代替这里解释的发生。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM