python - pytee can not produce proper output in python3 -
i have piece of code runs in python 2.7.5 doesn't work python 3.
the major problem tee.write
, can not write file.
this piece of code suppose write 20 letters a
file /tmp/tee-test-1
, /tmp/tee-test-2
not, 2 files empty…
could 1 give me advice?
import sys import os import subprocess #from netsa.util.shell import * string import template __author__ = 'brandon sandrowicz <brandon@sandrowicz.org>' __version__ = '0.1' valid_modes = ['a','w'] def create_tee(files, mode, buffer_size=128): if mode not in valid_modes: raise ioerror("only valid modes create_tee() are: %s" % ', '.join(valid_modes)) tee_list = [] file in files: if type(file) == str: fp = open(file, mode) tee_list.append(fp) else: tee_list.append(file) pipe_read, pipe_write = os.pipe() pid = os.fork() if pid == 0: # child -- read bytes pipe , write them specified # files. try: # close parent's end of pipe os.close(pipe_write) bytes = os.read(pipe_read, buffer_size) print (bytes) while(bytes): file in tee_list: file.write(bytes) file.flush() # todo maybe add in fsync() here if fileno() method # exists on file bytes = os.read(pipe_read, buffer_size) except: pass finally: os._exit(255) else: # parent -- return file object wrapper around pipe # child. return os.fdopen(pipe_write,'w') if __name__ == '__main__': files = [ '/tmp/tee-test-1', '/tmp/tee-test-2' ] num_chars = 100000 print("writing %d chars files (using create_tee):" % num_chars) file in files: print(" %s" % file) print() tee = create_tee(files,mode='a') #print("a" * num_chars, end=' ', file=tee) tee.write("a" * 20) tee.close() os.wait() filename in files: open(filename, 'r') fh: chars = len(fh.read()) print("file '%s' has %d chars" % (filename, chars))
ok, found problem interesting , challenging, , found out what's wrong, it's said in that document:
one common problem file opened in wrong mode. make sure open text files
't'
flag , binary files'b'
flag , have solved many problems.
so you're writing data b""
datatype, tried following:
file in files: if type(file) == str: fp = open(file, mode+'b') tee_list.append(fp) else: tee_list.append(file)
and works well:
file '/tmp/tee-test-1' has 20 chars file '/tmp/tee-test-2' has 20 chars
Comments
Post a Comment