-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConsole.py
More file actions
84 lines (68 loc) · 2.61 KB
/
Copy pathConsole.py
File metadata and controls
84 lines (68 loc) · 2.61 KB
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
# -*- coding: utf-8 -*-
import sys, codecs, os, os.path
from subprocess import *
class Console:
def __init__(self, charset = 'iso8859-1'):
self.writable = False
self.executable = True
self.logging = False
self.syscharset = charset
self.paths = []
self.current = None
self.log = []
def __repr__(self):
"""String representation."""
return '<%r: writable=%r, executable=%r, logging=%r, syscharset=%r, paths=%r, current=%r, log=%r>' % (
self.__class__.__name__, self.writable, self.executable, self.logging, self.syscharset, self.paths, self.current, self.log
)
def root(self, current):
if not os.path.isdir(current):
os.mkdir(current)
self.current = current
def write(self, line, prefix = u'[WRITE]: ', fd=None):
if self.writable:
if fd is not None:
out = sys.stdout
else:
out = fd
out.write((prefix + line).encode(self.syscharset))
out.write('\n')
if self.logging:
self.log.append(prefix + line)
self.log.append('\n')
def writeerr(self, line, prefix = u'[ERROR]: '):
self.write(line, prefix, sys.stderr)
def appendpath(self, path):
if isinstance(path, str):
self.paths.append([path])
elif isinstance(path, list):
self.paths.append(path)
def poppath(self, depth=0):
ret = []
if(depth==0):
ret = self.paths
self.paths = []
else:
for i in range(depth):
ret.append(self.paths.pop())
return ret
def execute(self, cmd):
cwd = os.getcwd()
line = ' '.join(cmd)
self.writeerr(line, u'[EXEC]: ')
if self.executable:
pathlist = []
for path in self.paths:
pathlist += path
envmap = os.environ.copy()
envmap['PATH'] = os.pathsep.join(map(lambda x: x.encode(self.syscharset), pathlist) + [envmap['PATH']])
if self.logging:
proc = Popen(line.encode(self.syscharset), shell=True, stdout=PIPE, stderr=STDOUT, cwd=self.current, env=envmap)
for line in proc.stdout:
self.write(line.decode(self.syscharset))
ret = proc.retcode
else:
ret = call(line.encode(self.syscharset), shell=True, cwd=self.current, env=envmap)
return ret
else:
return -1