2013-08-14 14 views
6

Ho bisogno di eseguire il loop sull'output di un comando. Ho pensato di usare subprocess.check_output, ora ho due problemi.loop python su sottoprocesso.check_output per riga

Ecco un file:

foo 
bar 

Ecco il mio script python:

import subprocess 

for line in subprocess.check_output(['cat', 'foo']): 
    print "%r" % line 

ed ecco cosa ottengo:

$ python subp.py 
'f' 
'o' 
'o' 
'\n' 
'b' 
'a' 
'r' 
'\n' 

mi aspetto:

$ python subp.py 
'foo\n' 
'bar\n' 

risposta

11

subprocess.check_output ([ 'gatto', 'foo']) restituisce una stringa: "foo \ nbar"

Così, il vostro ciclo for itera oltre la stringa, stampa ogni personaggio, uno per uno.

Il seguente dovrebbe risolvere il problema:

import subprocess 

print subprocess.check_output(['cat', 'foo']) 

È anche possibile fare:

import subprocess 

for line in subprocess.check_output(['cat', 'foo']).split('\n'): 
    print "%r" % line 
+1

potrebbe anche usare [ '.splitlines()'] (https://docs.python.org /library/stdtypes.html#str.splitlines) o 'p =' ['subprocess.Popen'] (https://docs.python.org/library/subprocess.html#popen-constructor)' (..., stdout = subprocess.PIPE); per la riga in p.stdout: ... ' – bufh