3

I build a script that should be used with git, so that output is sent to a pager after a git command. I would like to do this using Python.

I have a python script that writes to stdout. Now I would like to display its output in the pager the user has set in git.

I know I could always provide a wrapper script that does this:

git-whatever | less

Is there any way to do this from within python?

octopusgrabbus
  • 10,555
  • 15
  • 68
  • 131
Martin Ueding
  • 8,245
  • 6
  • 46
  • 92

2 Answers2

2

git likes to write stuff to temporary files, and then pass the name of the file on to git hooks. So following that pattern, you could just write your output to a temporary file, and call less with subprocess.Popen:

import subprocess
import tempfile

lines=(str(i) for i in range(1000))
f=tempfile.NamedTemporaryFile(mode='w')
f.write('\n'.join(lines))
f.flush()
proc=subprocess.Popen(['less',f.name])
proc.communicate()
f.close()  # deletes the temporary file
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
2

You do not even have to create the tempfile (using pipe instead):

import subprocess

proc=subprocess.Popen('less', stdin=subprocess.PIPE)
lines=(str(i) for i in range(1000))
proc.stdin.write('\n'.join(lines))
proc.stdin.close()
proc.communicate()
Misli
  • 36
  • 1