Python 3 writing to a pipe -
i'm trying write code put data pipe, , i'd solution python 2.6+ , 3.x compatible. example:
from __future__ import print_function import subprocess import sys if(sys.version_info > (3,0)): print ("using python3") def raw_input(*prmpt): """in python3, input behaves raw_input in python2""" return input(*prmpt) class pipe(object): def __init__(self,openstr): self.gnuprocess=subprocess.popen(openstr.split(), stdin=subprocess.pipe) def putinpipe(self,mystr): print(mystr, file=self.gnuprocess.stdin) if(__name__=="__main__"): print("this simple program echoes (control-d exit)") p=pipe("cat -") while(true): try: inpt=raw_input() except eoferror: break print('putting in pipe:%s'%inpt) p.putinpipe(inpt)
the above code works on python 2.6 fails in python 3.2 (note above code generated 2to3 -- messed little make python 2.6 compatible.)
traceback (most recent call last): file "test.py", line 30, in <module> p.putinpipe(inpt) file "test.py", line 18, in putinpipe print(mystr, file=self.gnuprocess.stdin) typeerror: 'str' not support buffer interface
i've tried bytes function (e.g. print(bytes(mystr,'ascii')) suggested here, typeerror: 'str' not support buffer interface doesn't seem work. suggestions?
the print
function converts arguments string representation, , outputs string representation given file. string representation of type str
both, python 2.x , python 3.x. in python 3.x, pipe accepts bytes
or buffer objects, won't work. (even if pass bytes
object print
, converted str
.)
a solution use write()
method instead (and flushing after writing):
self.gnuprocess.stdin.write(bytes(mystr + "\n", "ascii")) self.gnuprocess.stdin.flush()
Comments
Post a Comment