-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathguiStreams.py
109 lines (95 loc) · 2.9 KB
/
guiStreams.py
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
from tkinter import *
from tkinter.simpledialog import askstring
from tkinter.scrolledtext import ScrolledText
class GuiOutput:
font = ('courier', 9, 'normal')
def __init__(self, parent=None):
self.text = None
if parent: self.popupnow(parent)
def popupnow(self, parent=None):
if self.text: return
self.text = ScrolledText(parent or Toplevel())
self.text.config(font=self.font)
self.text.pack()
def write(self, text):
self.popupnow()
self.text.insert(END, str(text))
self.text.see(END)
self.text.update()
def writelines(self, lines):
for line in lines: self.write(line)
class GuiInput:
def __init__(self):
self.buff = ''
def inputLine(self):
line = askstring('GuiInput', 'Enter input line + <crlf> (cancel=eof)')
if line == None:
return ''
else:
return line + '\n'
def read(self, bytes=None):
if not self.buff:
self.buff = self.inputLine()
if bytes:
text = self.buff[:bytes]
self.buff = self.buff[bytes:]
else:
text = ''
line = self.buff
while line:
text = text + line
line = self.inputLine()
return text
def readline(self):
text = self.buff or self.inputLine()
self.buff = ''
return text
def readlines(self):
lines = []
while True:
next = self.readline()
if not next: break
lines.append(next)
return lines
def redirectedGuiFunc(func, *pargs, **kargs):
import sys
saveStreams = sys.stdin, sys.stdout
sys.stdin = GuiInput()
sys.stdout = GuiOutput()
sys.stderr = sys.stdout
result = func(*pargs, **kargs)
sys.stdin, sys.stdout = saveStreams
return result
def redirectedGuiShellCmd(command):
import os
input = os.popen(command, 'r')
output = GuiOutput()
def reader(input, output):
while True:
line = input.readline()
if not line: break
output.write(line)
reader(input, output)
if __name__ == '__main__':
def makeUpper():
while True:
try:
line = input('Line? ')
except:
break
print(line.upper())
print('end of line')
def makeLower(input, output):
while True:
line = input.readline()
if not line: break
output.write(line.lower())
print('end of line')
root = Tk()
Button(root, text='test streams',
command=lambda: redirectedGuiFunc(makeUpper)).pack(fill=X)
Button(root, text='test files',
command=lambda: makeLower(GuiInput(), GuiOutput())).pack(fill=X)
Button(root, text='test popen',
command=lambda: redirectedGuiShellCmd('dir *')).pack(fill=X)
root.mainloop()