2014-02-24 59 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