ipython重定向标准输出显示损坏

时间:2012-10-18 19:12:15

标签: stdout ipython

我正在使用python开发一个系统,我需要的一个功能是能够将控制台输出同时发送到控制台和用户指定的文件。这是复制MATLAB中的日记功能。我有以下内容在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;我的问题在于此。我可以完美地打开“日记”,没有错误但是控制台上的显示变得混乱。附带的屏幕截图显示了此screenshot。输出文件也变得类似乱码。当我用Diary(None)撤消重定向时,一切都恢复正常。我已经尝试编辑代码,以便它甚至不会写入文件,没有任何效果。似乎有些东西迫使不支持的字符集或我不理解的东西。

有人对此有所了解吗?

0 个答案:

没有答案