2013-10-30 71 views

回答

0
x = list() 

x.append(strings1) # use a loop of some sort to append your strings 
x.append(strings2) 
. 
. 
. 
x.append(stringsN) 

return x 
0

你可以臨時更改sys.stdout到自定義類:

import sys 

def fun(a,b): 
    print(a) 
    print(b) 

class Catcher: 
    def __init__(self): 
     self.res = [] 
     self.stdout = sys.stdout 
     sys.stdout = self 
    def write(self, chars): 
     self.res.append(chars) 
    def call(self, fun, *args, **kwargs): 
     fun(*args, **kwargs) 
     sys.stdout = self.stdout 
     return self.res 

print(Catcher().call(fun, "hello", b="world!")) 

=> ['hello', '\n', 'world!', '\n'] 
相關問題