我导入了readline,将定制的制表符补全添加到我的程序中。现在我需要保存程序的输出,但是任何重定向stdout的尝试都会破坏tab completion功能。你知道吗
我试过python3 script.py | tee txt.txt
这个开关似乎最接近打印到标准输出和文本文件,但它不起作用。你知道吗
下面是带有main函数调用的自定义tab完成类(以防万一):
import readline
class MyCompleter(object):
def __init__(self, options):
self.options = sorted(options)
def complete(self, text, state):
if state == 0:
if text:
self.matches = [s for s in self.options if s and s.startswith(text)]
else:
self.matches = self.options[:]
try:
return self.matches[state]
except IndexError:
return None
def readlineset(a): # function called from main to turn on tab completion
# a is list of strings
readline.set_completer(MyCompleter(a).complete)
readline.parse_and_bind('tab: complete')
这里有一个可能的解决方案:
sys.stdout.write
方法“monkey patch”,这样写到stdout
的任何东西也会被发送到一个文件。我承认这不太优雅,但很管用。;)我创建了
Logger
类a Context Manager,这样就可以在with
语句中使用它。你知道吗演示
mylog.txt文件
如果不想使用
with
,可以这样使用Logger
:相关问题 更多 >
编程相关推荐