python - 在 Python 中将当前标准输出分页至 less

标签 python python-3.x

我有一个这样的片段:

my_string = "foo bar"
def print_string(fd=sys.stdout):
    print(my_string, file=fd)

如何将 print_string 的输出通过管道传输到寻呼机,例如 less

我知道将 subprocess.Popenstdin=PIPE 一起使用,然后使用 proc.communicate(),但后来我只能直接写入my_string,而不能从现有描述符重定向。

虽然有点傻,但我尝试了以下方法;我对它不起作用并不感到惊讶:

proc = subprocess.Popen("less -".split(), stdin=sys.stdout)
print_string()
proc.wait()

Git 命令似乎有效地做了同样的事情:通过寻呼机传输其输出;我试图达到类似的效果。

最佳答案

Less 需要从“真实”标准输入中读取来获取按键信息,否则它无法对用户输入使用react。相反,您可以创建一个临时文件并让 less 读取:

import subprocess
import tempfile

with tempfile.NamedTemporaryFile("w") as f:
    f.write("hello world!")
    f.flush() // flush or otherwise the content 
              // might not be written when less tries to read
    p = subprocess.Popen(["/usr/bin/less", f.name])
    p.wait()

这可能会产生安全后果,最好在将临时文件用于 super 安全的东西之前阅读有关临时文件的文档。

我也不确定 git 是如何做到的,或者是否有更好的方法,但它在我的简短测试中有效。

关于python - 在 Python 中将当前标准输出分页至 less,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43875259/

相关文章:

python - 如何获取给定数字的约数列表?

python - 是否可以根据批处理标签(y_true)分布更新每批处理的学习率?

python-3.x - 无法使用pip在Windows上安装h5py

Python将字典中的负值更改为正值

python - 添加为子目录时找不到导入

python - SQLAlchemy 中的 GroupBy 和 Sum?

python - 如何在编码时阻止自己覆盖 Python 函数?

python - 有没有办法导出许多大小和位置完全相同的饼图/圆环图? (matplotlib)

Python - 为什么按值传递的 ndarray 在函数外部发生变化?

python - 熄灯