【问题标题】:How to obtain man page contents in Python?如何在 Python 中获取手册页内容?
【发布时间】:2012-09-27 22:42:47
【问题描述】:

我正在运行 linux,我想将一些手册页导入我的应用程序。

我想出了这个:

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

但这不好,人只显示第一页并阻止我的应用程序

如何使用 Python 获取手册页?

【问题讨论】:

  • 格式怎么样?你需要保留它,还是需要剥离它?

标签: python linux subprocess manpage


【解决方案1】:

试试:

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

相反—— “-P”选项覆盖了“man”命令使用的寻呼程序。

【讨论】:

    【解决方案2】:

    您可以使用check_output 获取命令的全部输出。此外,没有必要使用 shell,甚至可能使您的应用程序容易受到 shell injection attack 和 strongly discouraged 的攻击。

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

    请注意,使用man 将为您提供针对终端格式化的输出。如果你想让它的格式不同,你必须

    • 调用man -w <name>获取手册页的位置,
    • 可能解压手册页,
    • 使用-T 选项将其提供给groff 以选择所需的输出类型。

    调用groff 时,不要忘记加载正确的宏。

    在 FreeBSD 上,我倾向于使用 groff -Tlatin1 -mandoc <file> 来获取文本输出。

    【讨论】:

    • +1 用于处理格式化和提及groff -T...,并使用man -w 让man 查找并返回路径,然后自己处理。
    • 哦,当然还有提到shell=True 的安全隐患。我的 +3 按钮在哪里?
    • 我使用的是 Python 2.6 没有 subprocess.check_output() :]
    • @user775023 这是 CPython 中check_output() 的源代码:subprocess.py#l549。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-31
    • 1970-01-01
    • 2010-12-23
    • 1970-01-01
    • 2010-11-06
    • 1970-01-01
    • 2018-02-11
    相关资源
    最近更新 更多