1. 程式人生 > >python中print的不換行即時輸出解決方案

python中print的不換行即時輸出解決方案

class ChangeLine:
    NewLine = True

    @classmethod
    def write_out(self,str,typename = 0):
#   0 is "\n.....\n"
        if typename == 0:
            if self.NewLine == False:
                sys.stdout.write('\n')
                sys.stdout.flush()
            sys.stdout.write(str + '\n')
            sys.stdout.flush()
            self.NewLine = True
#   1 is "......."
        if typename == 1:
            sys.stdout.write(str)
            sys.stdout.flush()
            self.NewLine = False
#   2 is "\n......"
        if typename == 2:
            if self.NewLine == False:
                sys.stdout.write('\n')
                sys.stdout.flush()
            sys.stdout.write(str)
            sys.stdout.flush()
            self.NewLine = False
#   3 is "......\n"
        if typename == 3:
            sys.stdout.write(str + '\n')
            sys.stdout.flush()
            self.NewLine = True