用Python替换popen2的子进程

pro*_*eek 6 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()
Run Code Online (Sandbox Code Playgroud)

它运行良好,警告

~/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")
Run Code Online (Sandbox Code Playgroud)

unu*_*tbu 10

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)
Run Code Online (Sandbox Code Playgroud)