用Python替换popen2的子流程

用Python替换popen2的子流程,python,subprocess,Python,Subprocess,我试图从Fred Lunde的《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_l

我试图从Fred Lunde的《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.
在多处理模块中,有一种称为“池”的方法,考虑到您计划进行排序(不确定数据有多大,但…),它可能非常适合您的需要

它可以根据您的系统拥有的内核数对自身进行优化。i、 e.生成的进程数与核心数相同。当然,这是可定制的

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
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)
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