我正在尝试实现类似于git log
的方法,该方法仅在日志具有一定长度时才分页输出。如果您不熟悉git,那么我实际上是在尝试实现这一点:
python some_script.py | less
借助python2.6/pydoc.py中的分页实现的一些帮助,我得以提出以下建议:
import os
text = '...some text...'
pipe = os.popen('less', 'w')
pipe.write(text)
pipe.close()
效果很好,但是不推荐使用os.popen()。我已经考虑过写入一个临时文件并减少其路径调用,但这似乎并不理想。子流程有可能吗?还有其他想法吗?
编辑:
所以我已经使子流程工作了。我可以使用
Popen.communicate(text)
来给它文本变量,但是由于我真的想重定向打印语句,因此我决定这样做: import os, sys, subprocess, tempfile
page = True
if page:
path = tempfile.mkstemp()[1]
tmp_file = open(path, 'a')
sys.stdout = tmp_file
print '...some text...'
if page:
tmp_file.flush()
tmp_file.close()
p = subprocess.Popen(['less', path], stdin=subprocess.PIPE)
p.communicate()
sys.stdout = sys.__stdout__
当然,我最终将其包装为函数。有人看到这个问题吗?
最佳答案
使用subprocess.Popen代替。
http://docs.python.org/library/subprocess.html#subprocess-replacements
http://docs.python.org/library/subprocess.html#subprocess.Popen
os.popen文档中甚至对此有一个注释。
http://docs.python.org/library/os.html#os.popen
关于python - 从python分页输出,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6728661/