Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

subprocess replacement of popen2 with Python

I tried to run this code from the book 'Python Standard Library' of 'Fred Lunde'.

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

It runs well with a warning of

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

How to translate the previous function with subprocess? I tried as follows, but it doesn't work.

from subprocess import *

p = Popen("sort", shell=True, stdin=PIPE, stdout=PIPE, close_fds=True) 
p.stdin("foo\n")                #p.stdin("bar\n")
like image 852
prosseek Avatar asked Oct 08 '10 16:10

prosseek


1 Answers

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)
like image 64
unutbu Avatar answered Oct 14 '22 14:10

unutbu