我正在尝试实现类似于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__
当然,我最终会把它包装成函数。有没有人觉得这有问题?
发布于 2011-07-18 12:57:36
发布于 2013-08-14 22:10:19
这样如何:
import pydoc
text = '... some text ... '
pydoc.pager(text)
它(在我的opensuse linux机器上)将文本发送到一个分页程序(在我的例子中是‘less’),其工作方式与调用"help(... python command...)“相同。在Python解释器中。
发布于 2011-07-18 15:54:26
最好在代码中明确表示,这样就表明您使用了特殊的打印函数printc()
,而不是标准的打印函数。使用subprocess.call()
也是足够的(您不需要管道机械)。此外,您可以通过不存储临时文件的名称来保存变量:
from __future__ import print_function
import subprocess, tempfile
page = True # For tests
# Definition of a printc() function that prints to the correct output
if page:
tmp_file = open(tempfile.mkstemp()[1], 'w') # No need to store the name in a specific variable
def printc(*largs, **kwargs):
if 'file' not in kwargs: # The code can still use the usual file argument of print()
kwargs['file'] = tmp_file # Forces the output to go to the temp file
print(*largs, **kwargs)
else:
printc = print # Regular print
# Main program:
printc('...some text...', 'some more text', sep='/') # Python3 syntax
# Paging of the current contents of the temp file:
if page:
tmp_file.flush() # No need to close the file: you can keep printing to it
subprocess.call(['less', tmp_file.name]) # Simpler than a full Popen()
这样,您就可以获得Python3的print
函数的灵活性,它的代码可以显式地显示您正在做一些奇特的打印工作。与在代码的某些位置修改“全局”sys.stdout
变量相比,这在较大的程序中具有更好的伸缩性。
https://stackoverflow.com/questions/6728661
复制相似问题