[英]Python Sub Process with Tr Command
我在將tr命令插入子進程時遇到麻煩。
我有以下幾點:
process = subprocess.Popen('"tr < " + inputFile + " -d '\000' > " + nullFile', shell=True, stdout=subprocess.PIPE)
但不斷
TypeError: execv() arg 2 must contain only strings
誰能看到發生了什么事? 看起來可能是'和'問題,但不確定。
這樣解決:
command = r"tr -d '\000' < {0:s} > {1:s}".format(inputFile, nullFile)
process = subprocess.Popen(command)
process.wait()
您不需要shell=True
即可調用tr
命令:
#!/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)
反斜杠在Python字符串文字中是特殊的,因此要傳遞反斜杠,您需要對其進行轉義: '\\\\000'
或應使用原始字符串文字: r'\\000'
。
您在這里不需要外部過程。 您可以使用純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''))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.