I am having trouble inserting a tr command into a subprocess.
I have the following:
process = subprocess.Popen('"tr < " + inputFile + " -d '\000' > " + nullFile', shell=True, stdout=subprocess.PIPE)
but keep getting
TypeError: execv() arg 2 must contain only strings
Can anyone see whats going on? It looks like it may be ' and " issues but not sure.
Solved it this way:
command = r"tr -d '\000' < {0:s} > {1:s}".format(inputFile, nullFile)
process = subprocess.Popen(command)
process.wait()
You don't need shell=True
, to call tr
command:
#!/usr/bin/env python
from subprocess import check_call
with open('input', 'rb', 0) as input_file, \
open('output', 'wb', 0) as output_file:
check_call(['tr', '-d', r'\000'], stdin=input_file, stdout=output_file)
Backslash is special inside Python string literals and therefore to pass the backslash, you either need to escape it: '\\\\000'
or you should use a raw-string literal: r'\\000'
.
You don't need the external process here. You could remove zero bytes from a file using pure Python:
chunk_size = 1 << 15
with open('input', 'rb') as input_file, \
open('output', 'wb') as output_file:
while True:
data = input_file.read(chunk_size)
if not data: # EOF
break
output_file.write(data.replace(b'\0', b''))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.