2010-10-08 12 views
5

Ho provato a eseguire questo codice dal libro 'Python Standard Library' di 'Fred Lunde'.subprocess sostituzione di popen2 con Python

import popen2, string 

fin, fout = popen2.popen2("sort") 

fout.write("foo\n") 
fout.write("bar\n") 
fout.close() 

print fin.readline(), 
print fin.readline(), 
fin.close() 

funziona bene con un avvertimento di

 
~/python_standard_library_oreilly_lunde/scripts/popen2-example-1.py:1: 
DeprecationWarning: The popen2 module is deprecated. Use the subprocess module. 

Come tradurre la funzione precedente con sottoprocesso? Ho provato come segue, ma non funziona.

from subprocess import * 

p = Popen("sort", shell=True, stdin=PIPE, stdout=PIPE, close_fds=True) 
p.stdin("foo\n")    #p.stdin("bar\n") 
+0

* alcuni errori *? – SilentGhost

risposta

9
import subprocess 
proc=subprocess.Popen(['sort'],stdin=subprocess.PIPE,stdout=subprocess.PIPE) 
proc.stdin.write('foo\n') 
proc.stdin.write('bar\n') 
out,err=proc.communicate() 
print(out) 
0

all'interno del modulo multiprocessing c'è un metodo chiamato 'Pool' che potrebbe essere perfetto per le vostre esigenze considerando che si sta progettando di fare sorta (non so come enorme dati è, ma ...) .

Si è ottimizzato sul numero di core del sistema. cioè solo quanti processi vengono generati come il no. di core. Naturalmente questo è personalizzabile.

from multiprocessing import Pool 

def main(): 
    po = Pool() 
    po.apply_async(sort_fn, (any_args,), callback=save_data) 
    po.close() 
    po.join() 
    return 

def sort_fn(any_args): 
    #do whatever it is that you want to do in a separate process. 
    return data 

def save_data(data): 
    #data is a object. Store it in a file, mysql or... 
    return 
Problemi correlati