Ray's playground

 

Script Execution Context(Chapter 3 of Programming Python)

 1 import sys
 2 
 3 class Output:
 4     def __init__(self):
 5         self.text = ''
 6     def write(self, string):
 7         self.text += string
 8     def writelines(self, lines):
 9         for line in lines:
10             self.write(line)
11 
12 class Input:
13     def __init__(self, input=''):
14         self.text = input
15     def read(self, size=None):
16         if size == None:
17             res, self.text = self.text, ''
18         else:
19             res, self.text = self.text[:size], self.text[size:]
20     def readline(self):
21         eoln = self.text.find('\n')
22         if eoln == -1:
23             res. self.text = self.text, ''
24         else:
25             res, self.text = self.text[:eoln+1], self.text[eoln+1:]
26 
27 def redirect(function, pargs, kargs, input):
28     savestreams = sys.stdin, sys.stdout
29     sys.stdin = Input(input)
30     sys.stdout = Output()
31     try:
32         result = function(*pargs, **kargs)
33     finally:
34         sys.stdin, sys.stdout = savestreams
35     return (result, output)

posted on 2011-04-05 09:56  Ray Z  阅读(275)  评论(0编辑  收藏  举报

导航