2014-02-24 40 views
2

如何使用子进程库而不是命令来编写以下行。 这个想法是得到相同的结果,但使用子进程。从命令到子进程

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

回答

2

等效命令commands.getoutputsubprocess.check_output

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

,如果我使用的外壳会发生哪些变化=,而不是假壳=真? –

+0

请参阅下面的答案。默认情况下,你需要分割你的命令。 Whit shell = True,你可以把它写成一个字符串。请参阅http://docs.python.org/2/library/subprocess.html#subprocess.check_output –

+0

@En_Py'shell = False'期望您传递参数列表而不是字符串,并且重定向操作符将不起作用'shell = False'。检查它是有据可查的子流程文档。 –

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 
+1

用于模拟'{cmd; } 2>&1'(包括'stderr')。注意:'commands.getoutput()'带有换行符。看看[command.getoutput()'是如何用'subprocess'模块实现的](http://hg.python.org/cpython/file/a7a62a88380a/Lib/subprocess.py#l692) – jfs

0

你不需要外壳在这种情况下,运行tr命令。既然你已经重定向了子进程的标准输出,你也不必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子进程作为一个单独的字符串:

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"")) 
+0

这也是工作很好,只使用Python。哇! –

+0

但我不明白什么chunksize = 1 << 15函数是。 –

+0

@En_Py:'1 << 15'是'2 ** 15',即'32768'。通常这个值(缓冲区大小)是2的幂。你可以使用'chunksize = io.DEFAULT_BUFFER_SIZE'来提高可读性(改变'chunksize'可能会影响时间性能)。代码重复执行'chunk = input_file.read(chunksize)'直到EOF。 – jfs