[英]Python Sub Process with Tr Command
I am having trouble inserting a tr command into a subprocess. 我在将tr命令插入子进程时遇到麻烦。
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: 您不需要
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)
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'
. 反斜杠在Python字符串文字中是特殊的,因此要传递反斜杠,您需要对其进行转义:
'\\\\000'
或应使用原始字符串文字: r'\\000'
。
You don't need the external process here. 您在这里不需要外部过程。 You could remove zero bytes from a file using pure Python:
您可以使用纯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.