how to handle unix command having \x in python code -
i want execute command
sed -e 's/\x0//g' file.xml
using python code.
but getting error valueerror: invalid \x escape
you not showing python code, there room speculation here.
but first, why file contain null bytes in first place? not valid xml file. can fix process produces file?
secondly, why want sed
? using python; use native functions sort of processing. if expect read file line line, like
with open('file.xml', 'r') xml: line in xml: line = line.replace('\x00', '') # ... processing here
or if expect whole file 1 long byte string:
with open('file.xml', 'r') handle: xml = handle.read() xml = xml.replace('\x00', '')
if want use external program, tr
more natural sed
. syntax use depends on dialect of tr
or sed
well, fundamental problem backslashes in python strings interpreted python. if there shell involved, need take shell's processing account. in simple terms, try this:
os.system("sed -e 's/\\x0//g' file.xml")
or this:
os.system(r"sed -e 's/\x0//g' file.xml")
here, single quotes inside double quotes required because shell interprets this. if use form of quoting, need understand shell's behavior under quoting mechanism, , how interacts python's quoting. don't need shell here in first place, , i'm guessing in reality processing looks more this:
sed = subprocess.popen(['sed', '-e', r's/\x0//g', 'file.xml'], stdin=subprocess.pipe, stdout=subprocess.pipe, stderr=subprocess.pipe) result, err = sed.communicate()
because no shell involved here, need worry python's quoting. before, can relay literal backslash sed
either doubling it, or using r'...'
raw string.
Comments
Post a Comment