2014-01-15 29 views
4

我想要做的事很簡單。我想用python的subprocess模塊調用下面的命令。使用大於subprocess.call的操作符

cat /path/to/file_A > file_B 

的命令只是作品和複印件在當前工作目錄中的file_A內容file_B。但是,當我嘗試在腳本中使用subprocess模塊調用此命令時,它會出錯。以下是我在做什麼:

import subprocess 

subprocess.call(["cat", "/path/to/file_A", ">", "file_B"]) 

,我得到以下錯誤:

cat: /path/to/file_A: No such file or directory 
cat: >: No such file or directory 
cat: file_B: No such file or directory 

我究竟做錯了什麼?如何使用子進程模塊call命令使用大於運算符?

回答

8

>輸出重定向是外殼功能,但subprocess.call()args列表和shell=False(默認值)不使用外殼。

你必須在這裏使用shell=True

subprocess.call("cat /path/to/file_A > file_B", shell=True) 

或者更好的是,使用subprocess一個命令的輸出重定向到一個文件:

with open('file_B', 'w') as outfile: 
    subprocess.call(["cat", "/path/to/file_A"], stdout=outfile) 

如果你只是複製文件,使用shutil.copyfile() functionPython將文件複製到:

import shutil 

shutil.copyfile('/path/to/file_A', 'file_B') 
+0

我不完全複製一個文件,但使用'sed'提取一部分。 – Amyth

+0

@Amyth:當然,Python也可以提取。 –

0

加成的Martijn的回答是:

你可以做同樣的事情cat自己:

with open("/path/to/file_A") as file_A: 
    a_content = file_A.read() 
with open("file_B", "w") as file_B: 
    file_B.write(a_content) 
+1

'shutil.copyfile()'函數實質上做到了這一點,但更有效率(使用緩衝區而不是讀取內存中的整個文件)。 –

+0

是的。只是想表明額外的可能性。 –