import sys
class Wrap:
def __init__(self):
self.last_line = None
self._next_line = ''
def write(self, text, *args, **kwargs):
sys.__stdout__.write(text, *args, **kwargs)
self._next_line += text
try:
self.last_line = self._next_line.split('\n')[-2]
self.next_line = self._next_line.split('\n')[-1]
except IndexError:
# We did not have \n yet and _next_line did not split
# into at least two items
pass
save_stdout = sys.stdout
sys.stdout = Wrap()
print('xxx\nzzz') # This was that function you wanted to call
last_line = sys.stdout.last_line
sys.stdout = save_stdout
print(last_line)
好吧,这不太好,但是你可以(希望写的东西不会搞笑)尝试劫持
sys.stdout.write()
(或者stderr
,这取决于你写脚本的地方)。你知道吗这可能是一种方法,尽管很难看:
这将给您
zzz
作为输出。也就是说,最后一行打印(不添加换行符),而sys.stdout
是我们的包装。你知道吗当然,您可以只编写一个函数包装器,并使用它来规范化黑客行为。你知道吗
相关问题 更多 >
编程相关推荐