繁体   English   中英

Tr命令的Python子进程

[英]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.

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