Pyte无法在python3中生成正确的输出
我有一段代码在Python2.7.5中运行良好,但在Python3中不起作用 主要问题是tee.write,它无法写入文件 这段代码假设将20个字母a写入文件/tmp/tee-test-1和/tmp/tee-test-2,但事实并非如此,这两个文件是空的 谁能给我一些建议吗Pyte无法在python3中生成正确的输出,python,python-3.x,Python,Python 3.x,我有一段代码在Python2.7.5中运行良好,但在Python3中不起作用 主要问题是tee.write,它无法写入文件 这段代码假设将20个字母a写入文件/tmp/tee-test-1和/tmp/tee-test-2,但事实并非如此,这两个文件是空的 谁能给我一些建议吗 import sys import os import subprocess #from netsa.util.shell import * from string import Template __author__
import sys
import os
import subprocess
#from netsa.util.shell import *
from 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 to create_tee() are: %s" % ', '.join(valid_modes))
tee_list = []
for 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 from the pipe and write them to the specified
# files.
try:
# Close parent's end of the pipe
os.close(pipe_write)
bytes = os.read(pipe_read, buffer_size)
print (bytes)
while(bytes):
for file in tee_list:
file.write(bytes)
file.flush()
# TODO maybe add in fsync() here if the fileno() method
# exists on file
bytes = os.read(pipe_read, buffer_size)
except:
pass
finally:
os._exit(255)
else:
# Parent -- Return a file object wrapper around the pipe to the
# 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 to files (using create_tee):" % num_chars)
for 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()
for filename in files:
with open(filename, 'r') as fh:
chars = len(fh.read())
print("File '%s' has %d chars" % (filename, chars))
好的,我发现这个问题很有趣,也很有挑战性,最后我发现了问题所在,如: 一个常见的问题是文件以错误的模式打开。确保打开带有“t”标志的文本文件和带有“b”标志的二进制文件,这样就解决了许多问题 因此,当您以b数据类型写入数据时,我尝试了以下方法:
for file in files:
if type(file) == str:
fp = open(file, mode+'b')
tee_list.append(fp)
else:
tee_list.append(file)
而且效果很好:
File '/tmp/tee-test-1' has 20 chars
File '/tmp/tee-test-2' has 20 chars
定义不起作用。你能编辑你得到的错误吗?这段代码假设在文件'/tmp/tee-test-1''/tmp/tee-test-2'中写入20个字母a,但是它没有,这两个文件是空的,只是测试了它,实际上,它在py2和py3中的行为不同…