File size: 2,409 Bytes
719d0db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import os
import sys
import tempfile

# for stopping std out from concorde solver
# https://github.com/machine-reasoning-ufrgs/TSP-GNN/blob/master/redirector.py
STDOUT = 1
STDERR = 2

class Redirector(object):
    def __init__(self, fd=STDOUT):
        self.fd = fd
        self.started = False

    def start(self):
        if not self.started:
            self.tmpfd, self.tmpfn = tempfile.mkstemp()

            self.oldhandle = os.dup(self.fd)
            os.dup2(self.tmpfd, self.fd)
            os.close(self.tmpfd)

            self.started = True

    def flush(self):
        if self.fd == STDOUT:
            sys.stdout.flush()
        elif self.fd == STDERR:
            sys.stderr.flush()

    def stop(self):
        if self.started:
            self.flush()
            os.dup2(self.oldhandle, self.fd)
            os.close(self.oldhandle)
            tmpr = open(self.tmpfn, 'rb')
            output = tmpr.read()
            tmpr.close()  # this also closes self.tmpfd
            os.unlink(self.tmpfn)

            self.started = False
            return output
        else:
            return None

class RedirectorOneFile(object):
    def __init__(self, fd=STDOUT):
        self.fd = fd
        self.started = False
        self.inited = False

        self.initialize()

    def initialize(self):
        if not self.inited:
            self.tmpfd, self.tmpfn = tempfile.mkstemp()
            self.pos = 0
            self.tmpr = open(self.tmpfn, 'rb')
            self.inited = True

    def start(self):
        if not self.started:
            self.oldhandle = os.dup(self.fd)
            os.dup2(self.tmpfd, self.fd)
            self.started = True

    def flush(self):
        if self.fd == STDOUT:
            sys.stdout.flush()
        elif self.fd == STDERR:
            sys.stderr.flush()

    def stop(self):
        if self.started:
            self.flush()
            os.dup2(self.oldhandle, self.fd)
            os.close(self.oldhandle)
            output = self.tmpr.read()
            self.pos = self.tmpr.tell()
            self.started = False
            return output
        else:
            return None

    def close(self):
        if self.inited:
            self.flush()
            self.tmpr.close()  # this also closes self.tmpfd
            os.unlink(self.tmpfn)
            self.inited = False
            return output
        else:
            return None