2010-02-26 102 views
14

我不確定我的標題是否正確。 我在做什麼是寫一個python腳本來自動化我的一些代碼寫作。 所以我通過.h文件解析。 但我想在開始之前展開所有宏。 所以我想做一個調用外殼:將os.popen(命令)讀入字符串

gcc -E myHeader.h 

原本應該出來把myHeader.h一職前處理版本到標準輸出。 現在我想將所有輸出直接讀入一個字符串中作進一步處理。 我讀過,我可以用popen做到這一點,但我從來沒有使用管道對象。

我如何做到這一點?

+1

重複:http://stackoverflow.com/search?q=%5Bpython%5D+subprocess+output,http://stackoverflow.com/questions/1180606/using-subprocess-popen-for即使如此,爲了清楚和充分的問題+1,以及「post p再加工」。 :) – 2010-02-26 04:22:54

回答

20

os.popen函數只是返回一個類文件對象。您可以使用它像這樣:

import os 

process = os.popen('gcc -E myHeader.h') 
preprocessed = process.read() 
process.close() 

正如其他人所說,你應該使用subprocess.Popen。它的設計是的os.popen。 Python文檔有一個section describing how to switch over

15
import subprocess 

p = subprocess.popen('gcc -E myHeader.h'.split(), 
        stdout=subprocess.PIPE) 
preprocessed, _ = p.communicate() 

字符串preprocessed現在無數的例子有你需要的預處理源 - 你已經使用了「正確」(現代)的方式以殼爲一個子過程,而不是舊的不那麼喜歡,os.popen

+0

非常好的例子。有沒有辦法將stdout和stderr流分開? – smith324 2011-04-05 06:19:21

2

os.popen()自Python 2.6以來已被棄用。您現在應該使用模塊來代替:http://docs.python.org/2/library/subprocess.html#subprocess.Popen

import subprocess 

command = "gcc -E myHeader.h" # the shell command 
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=None, shell=True) 

#Launch the shell command: 
output = process.communicate() 

print output[0] 

在POPEN構造,如果,你應該通過命令作爲一個字符串,而不是作爲一個序列。否則,只拆分命令到列表:

command = ["gcc", "-E", "myHeader.h"] # the shell command 
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=None) 

如果你也需要閱讀標準錯誤,進入POPEN初始化,您可以設置標準錯誤subprocess.PIPEsubprocess.STDOUT

import subprocess 

command = "gcc -E myHeader.h" # the shell command 
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) 

#Launch the shell command: 
output, error = process.communicate()