我正在用 python 开发一个系统,我需要的一个功能是能够让控制台输出同时发送到控制台和用户指定的文件。这是在 MATLAB 中复制 Diary 函数。我的以下内容在 Windows 上的 IDLE 和 ubuntu 中的 python cmdline 上都运行良好(这都存在于一个被加载的模块中):
class diaryout(object):
def __init__(self):
self.terminal = sys.stdout
self.save = None
def __del__(self):
try:
self.save.flush()
self.save.close()
except:
# do nothing, just catch the error; maybe it self was instantiated, but never opened
1/1
self.save = None
def dclose(self):
self.__del__()
def write(self, message):
self.terminal.write(message)
self.save.write(message)
def dopen(self,outfile):
self.outfile = outfile
try:
self.save = open(self.outfile, "a")
except Exception, e:
# just pass out the error here so the Diary function can handle it
raise e
def Diary(outfile = None):# NEW TO TEST
global this_diary
if outfile == None:
# None passed, so close the diary file if one is open
if isinstance(this_diary, diaryout):
sys.stdout = this_diary.terminal # set the stdout back to stdout
this_diary.dclose() # flush and close the file
this_diary = None # "delete" it
else:
# file passed, so let's open it and set it for the output
this_diary = diaryout() # instantiate
try:
this_diary.dopen(outfile) # open & test that it opened
except IOError:
raise IOError("Can't open %s for append!"%outfile)
this_dairy=none # must uninstantiate it, since already did that
except TypeError:
raise TypeError("Invalid input detected - must be string filename or None: %s"%Diary.__doc__)
this_dairy=none # must uninbstantiate it, since already did that
sys.stdout = this_diary # set stdout to it
远远优于 IDLE 和普通的 python cmline,我使用的是 ipython;这就是我的问题所在。我可以完美无误地打开“日记”,但控制台上的显示会混乱。随附的屏幕截图显示了这一点。输出文件也变得类似乱码。当我使用 撤消重定向时,一切都恢复正常Diary(None)
。我已经尝试编辑代码,使其甚至永远不会写入文件,没有任何效果。似乎有些东西正在强制使用不受支持的字符集或我不理解的东西。
有人对此有任何想法吗?