我有一个这样的片段:
my_string = "foo bar"
def print_string(fd=sys.stdout):
print(my_string, file=fd)
如何将 print_string
的输出通过管道传输到寻呼机,例如 less
?
我知道将 subprocess.Popen
与 stdin=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/