从命令到子进程

时间:2014-02-24 13:24:07

标签: python command subprocess

如何使用子进程库而不是命令编写以下行。 我们的想法是使用子流程获得相同的结果。

commands.getoutput('tr -d "\'" < /tmp/file_1.txt > /tmp/file_2.txt')

3 个答案:

答案 0 :(得分:2)

commands.getoutput的等效命令是subprocess.check_output

from subprocess import check_output
out = check_output('tr -d "\'" < /tmp/file_1.txt > /tmp/file_2.txt', shell=True)

答案 1 :(得分:1)

import subprocess    

p=subprocess.Popen('tr -d "\'" < /tmp/file_1.txt > /tmp/file_2.txt',shell=True,stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output=p.communicate()[0]
print "o", output

答案 2 :(得分:0)

在这种情况下,您不需要shell来运行tr命令。因为你已经重定向了子进程'stdout;你也不需要subprocess.check_output()

from subprocess import check_call

with open("/tmp/file_1.txt", "rb") as input_file:
    with open("/tmp/file_2.txt", "wb") as output_file:
        check_call(["tr", "-d", "'"], stdin=input_file, stdout=output_file)

注意:与commands.getoutput()不同,它不捕获stderr。如果您希望将子进程的stderr作为单独的字符串:

from subprocess import Popen, PIPE

with open("/tmp/file_1.txt", "rb") as input_file:
    with open("/tmp/file_2.txt", "wb") as output_file:
        p = Popen(["tr", "-d", "'"], stdin=input_file, stdout=output_file,
                  stderr=PIPE)
stderr_data = p.communicate()[1]

此外,您可以使用纯Python替换tr调用:

from functools import partial

chunksize = 1 << 15
with open("/tmp/file_1.txt", "rb") as input_file:
    with open("/tmp/file_2.txt", "wb") as output_file:
         for chunk in iter(partial(input_file.read, chunksize), b''):
             output_file.write(chunk.replace(b"'", b""))
相关问题