在现有的代码片段中,我有
import sys
from code import InteractiveConsole
class FileCacher:
"Cache the stdout text so we can analyze it before returning it"
def __init__(self):
self.reset()
def reset(self):
self.out = []
def write(self, line):
self.out.append(line)
def flush(self):
output = '\n'.join(self.out)
self.reset()
return output
class Shell(InteractiveConsole):
"Wrapper around Python that can filter input/output to the shell"
def __init__(self):
self.stdout = sys.stdout
self.cache = FileCacher()
InteractiveConsole.__init__(self)
return
def get_output(self):
sys.stdout = self.cache
def return_output(self):
sys.stdout = self.stdout
def push(self, line):
self.get_output()
# you can filter input here by doing something like
# line = filter(line)
InteractiveConsole.push(self, line)
self.return_output()
output = self.cache.flush()
# you can filter the output here by doing something like
# output = filter(output)
print output # or do something else with it
return
if __name__ == '__main__':
sh = Shell()
sh.interact()
如果 IPython 可用,如何修改它以使用 IPython 的交互式 shell,而不更改其余代码(如果可能)。
我尝试将第 2 行 from code import InteractiveConsole
替换为 from IPython.core import Interactiveshell as InteractiveConsole
但显然,它不是一个可以直接互换的类。
执行此操作的最佳方法是什么(对代码库的其余部分进行最小的更改),当 IPython
存在吗?
最佳答案
这是我自己的尝试:-
import sys
from code import InteractiveConsole
class FileCacher:
"Cache the stdout text so we can analyze it before returning it"
def __init__(self):
self.reset()
def reset(self):
self.out = []
def write(self, line):
self.out.append(line)
def flush(self):
output = '\n'.join(self.out)
self.reset()
return output
class Shell(InteractiveConsole):
"Wrapper around Python that can filter input/output to the shell"
def __init__(self):
self.stdout = sys.stdout
self.cache = FileCacher()
InteractiveConsole.__init__(self)
return
def get_output(self):
sys.stdout = self.cache
def return_output(self):
sys.stdout = self.stdout
def push(self, line):
self.get_output()
# you can filter input here by doing something like
# line = filter(line)
InteractiveConsole.push(self, line)
self.return_output()
output = self.cache.flush()
# you can filter the output here by doing something like
# output = filter(output)
print output # or do something else with it
return
if __name__ == '__main__':
try:
import IPython
IPython.embed()
except:
sh = Shell()
sh.interact()
这似乎工作正常,但我可能丢失了缓存
和stdout
自定义方法/功能。
欢迎任何批评、编辑和改进建议!
关于python - 如果 IPython 存在,则可将 IPython 与代码模块互换使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10300510/