2010-02-26 8 views
14

Non sono sicuro che il mio titolo sia giusto. Quello che sto facendo è scrivere uno script python per automatizzare parte del mio codice scritto. Quindi sto analizzando un file .h. ma voglio espandere tutte le macro prima di iniziare. quindi voglio fare una chiamata alla shell a:leggendo un os.popen (comando) in una stringa

gcc -E myHeader.h 

Che dovrebbe mettere fuori la versione post pre-elaborato di myHeader.h stdout. Ora voglio leggere tutto ciò che viene emesso direttamente in una stringa per un'ulteriore elaborazione. Ho letto che posso farlo con popen, ma non ho mai usato oggetti pipe.

come faccio?

+1

duplicati: http://stackoverflow.com/search?q=%5Bpython%5D+subprocess+output, http://stackoverflow.com/questions/1180606/using-subprocess-popen-for -processo-con-grande-uscita Anche così, +1 per essere chiari e ben richiesti, e per "post p ritrattato". :) –

risposta

20

La funzione os.popen restituisce solo un oggetto simile a un file. Si può usare in questo modo:

import os 

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

Come altri hanno detto, si dovrebbe utilizzare subprocess.Popen. È progettato per essere un safer version di os.popen. I documenti Python hanno un section describing how to switch over.

15
import subprocess 

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

String preprocessed ora è la fonte pre-elaborato si richiede - e hai usato il modo "giusto" (moderna) per shell a un sottoprocesso, piuttosto che vecchio non così amato-più os.popen.

+0

Esempio molto bello. C'è un modo per separare i flussi stdout e stderr? – smith324

2

Il os.popen() è stata deprecata dal Python 2.6. Ora si dovrebbe utilizzare il modulo sottoprocesso invece: 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] 

Nel costruttore Popen, se guscio è vero, si dovrebbe passare il comando come una stringa piuttosto che come una sequenza. In caso contrario, basta dividere il comando in una lista:

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

Se avete bisogno di leggere anche l'errore standard, nel l'inizializzazione Popen, è possibile impostare stderr-subprocess.PIPE o per subprocess.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() 
Problemi correlati