3

im running linux and i want to import some man pages to my application.

i came up with this:

p = subprocess.Popen(('man %s' % manTopic,), shell = True, stdout = subprocess.PIPE)
stdout, stderr = p.communicate()
if stdout:

but its no good, man is displaying only first page and blocks my applicationon

How can i obtain man page with Python?

BPS
  • 1,133
  • 1
  • 17
  • 38

2 Answers2

9

You can grab the whole output of a command with check_output. Furthermore, using a shell is not necessary and might even make your application vulnerable to a shell injection attack and is strongly discouraged.

import subprocess

pagename = 'man'
manpage = subprocess.check_output(['man', pagename])

Note that using man will give you output formatted for a terminal. If you want to have it formatted differently, you'll have to

  • call man -w <name> to get the location of the manpage,
  • probably decompress the manual page,
  • feed it to groff using the -T option to select the type of output you want.

When calling groff, don't forget to load the correct macro's.

On FreeBSD I tend use groff -Tlatin1 -mandoc <file> to get text output.

Roland Smith
  • 42,427
  • 3
  • 64
  • 94
  • +1 for dealing with formatting and mentioning `groff -T...`, and using `man -w` to let `man` do the lookup and return the path, but then process it yourself. – Lukas Graf Oct 07 '12 at 13:03
  • Oh, and for mentioning the security implications of `shell=True` of course. Where's my +3 button? – Lukas Graf Oct 07 '12 at 13:04
  • I'm using Python 2.6 there is no subprocess.check_output() :] – BPS Oct 07 '12 at 13:07
  • @user775023 Here's the source code for `check_output()` in CPython: [subprocess.py#l549](http://hg.python.org/cpython/file/e11642068f85/Lib/subprocess.py#l549). – Lukas Graf Oct 07 '12 at 13:10
3

Try:

p = subprocess.Popen(('man -P cat %s' % manTopic,), shell = True)
stdout, stderr = p.communicate()
if stdout:

instead -- the "-P" option overrides the pager program used by the "man" command.

jsbueno
  • 99,910
  • 10
  • 151
  • 209