zhongrj
2025-11-24 276323dce9613867abb3f58a4cc2abbfb2fd0dea
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import os
import logging
logger = logging.getLogger('app.logger')
 
class Console:
    def __init__(self, file):
        self.file = file
        self.base_dir = os.path.dirname(self.file)
        self.parent_dir = os.path.dirname(self.base_dir)
 
    def __repr__(self):
        return "<Console output: %s>" % self.file
 
    def __str__(self):
        if not os.path.isfile(self.file):
            return ""
 
        try:
            with open(self.file, 'r', encoding="utf-8") as f:
                return f.read()
        except IOError:
            logger.warn("Cannot read console file: %s" % self.file)
            return ""
 
    def __add__(self, other):
        self.append(other)
        return self
 
    def output(self):
        return str(self)
 
    def append(self, text):
        if os.path.isdir(self.parent_dir):
            try:
                # Write
                if not os.path.isdir(self.base_dir):
                    os.makedirs(self.base_dir, exist_ok=True)
                
                with open(self.file, "a", encoding="utf-8") as f:
                    f.write(text)
            except IOError:
                logger.warn("Cannot append to console file: %s" % self.file)
 
    def reset(self, text = ""):
        if os.path.isdir(self.parent_dir):
            try:
                if not os.path.isdir(self.base_dir):
                    os.makedirs(self.base_dir, exist_ok=True)
                
                with open(self.file, "w", encoding="utf-8") as f:
                    f.write(text)
            except IOError:
                logger.warn("Cannot reset console file: %s" % self.file)
 
    def delink(self):
        try:
            if os.path.isfile(self.file) and os.stat(self.file).st_nlink > 1:
                with open(self.file, "r", encoding="utf-8") as f:
                    text = f.read()
                os.unlink(self.file)
                with open(self.file, "w", encoding="utf-8") as f:
                    f.write(text)
        except OSError:
            logger.warn("Cannot delink console file: %s" % self.file)