2010-10-08 79 views
5

popen2的我試圖運行從書的「弗雷德·倫德」 Python標準庫「的代碼。子替換使用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() 

它與

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

警告如何翻譯與子先前的功能運行良好?我嘗試如下,但它不起作用。

from subprocess import * 

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

*有些錯誤*? – SilentGhost 2010-10-08 16:44:14

回答

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

內多模塊有一個叫做「池」的方法,這可能是最適合你的需要考慮,你打算做排序(不知道如何將數據巨大的,但是......) 。

這是優化自身核心系統擁有的數量。即只有當許多過程產生時纔會產生。的核心。當然這是可定製的。

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