如何用脚本快速获取帮助文档

wen 实用脚本 2

本文目录导读:

如何用脚本快速获取帮助文档

  1. Python 脚本(通用性强)
  2. Bash 脚本(Linux/Unix)
  3. Node.js 脚本
  4. PowerShell 脚本(Windows)
  5. 跨平台通用脚本(Python)
  6. 快速使用示例

Python 脚本(通用性强)

import pydoc
import sys
import subprocess
import inspect
def quick_help(object_name, module_name=None):
    """
    快速获取 Python 对象帮助文档
    """
    try:
        if module_name:
            # 动态导入模块
            module = __import__(module_name, fromlist=[object_name])
            obj = getattr(module, object_name)
        else:
            # 在当前环境查找
            obj = eval(object_name)
        # 获取帮助信息
        help_info = pydoc.render_doc(obj)
        print(help_info[:2000])  # 限制输出长度
    except Exception as e:
        print(f"获取帮助失败: {e}")
# 使用示例
if __name__ == "__main__":
    # 获取字符串方法帮助
    quick_help("str.split")
    # 获取模块帮助
    quick_help("os", "os")

Bash 脚本(Linux/Unix)

#!/bin/bash
# script_help.sh - 快速获取命令帮助
get_help() {
    local cmd="$1"
    # 多种帮助方式
    echo "=== 尝试获取 $cmd 的帮助文档 ==="
    # 1. 内建帮助
    if type "$cmd" 2>/dev/null | grep -q "builtin"; then
        help "$cmd" 2>/dev/null | head -20
        return
    fi
    # 2. 尝试不同帮助选项
    for flag in "--help" "-h" "-?" "/?"; do
        if $cmd "$flag" 2>/dev/null | head -20; then
            return
        fi
    done
    # 3. man 页面
    if man "$cmd" 2>/dev/null >/dev/null; then
        man "$cmd" | head -30
        return
    fi
    echo "未找到帮助文档"
}
# 主函数
main() {
    if [ $# -eq 0 ]; then
        echo "用法: $0 <命令名>"
        exit 1
    fi
    get_help "$1"
}
main "$@"

Node.js 脚本

#!/usr/bin/env node
const { execSync } = require('child_process');
const path = require('path');
const fs = require('fs');
/**
 * 快速获取帮助文档
 */
class HelpScraper {
    constructor() {
        this.helpSources = {
            npm: (module) => this.getNpmHelp(module),
            man: (command) => this.getManHelp(command),
            info: (command) => this.getInfoHelp(command),
            builtin: (command) => this.getBuiltinHelp(command)
        };
    }
    getNpmHelp(module) {
        try {
            const output = execSync(`npm help ${module} --json 2>/dev/null`, {
                encoding: 'utf8'
            });
            return output;
        } catch {
            return null;
        }
    }
    getManHelp(command) {
        try {
            const output = execSync(`man ${command} 2>/dev/null | head -30`, {
                encoding: 'utf8'
            });
            return output;
        } catch {
            return null;
        }
    }
    getInfoHelp(command) {
        try {
            const output = execSync(`info ${command} 2>/dev/null`, {
                encoding: 'utf8'
            });
            return output;
        } catch {
            return null;
        }
    }
    getBuiltinHelp(command) {
        try {
            const output = execSync(`help ${command} 2>/dev/null`, {
                encoding: 'utf8'
            });
            return output;
        } catch {
            return null;
        }
    }
    async getHelp(target) {
        console.log(`\n🔍 正在获取 "${target}" 的帮助文档...\n`);
        // 尝试所有来源
        for (const [source, handler] of Object.entries(this.helpSources)) {
            const result = handler(target);
            if (result) {
                console.log(`📚 来源: ${source}`);
                console.log('─'.repeat(50));
                console.log(result.substring(0, 1000));
                console.log('─'.repeat(50));
                return;
            }
        }
        console.log(`❌ 未找到 "${target}" 的帮助文档`);
    }
}
// 主程序
const help = new HelpScraper();
const target = process.argv[2] || 'bash';
help.getHelp(target).catch(console.error);

PowerShell 脚本(Windows)

# quick_help.ps1
param(
    [Parameter(Mandatory=$true)]
    [string]$Command,
    [switch]$Online,
    [int]$Lines = 20
)
function Get-QuickHelp {
    param($Cmd)
    Write-Host "`n=== 获取 '$Cmd' 的帮助 ===" -ForegroundColor Cyan
    # 1. 尝试 Get-Help
    try {
        $help = Get-Help $Cmd -ErrorAction Stop
        Write-Host "`n📖 PowerShell 帮助:" -ForegroundColor Green
        $help | Select-Object -First $Lines
        return
    }
    catch {}
    # 2. 尝试外部命令帮助
    try {
        $output = & $Cmd --help 2>&1
        Write-Host "`n📖 --help 输出:" -ForegroundColor Green
        $output | Select-Object -First $Lines
        return
    }
    catch {}
    Write-Host "❌ 未找到帮助" -ForegroundColor Red
}
# 主逻辑
if ($Online) {
    # 在线帮助
    $url = "https://learn.microsoft.com/en-us/powershell/module/?term=$Command"
    Write-Host "打开在线帮助: $url" -ForegroundColor Yellow
    Start-Process $url
}
else {
    # 本地帮助
    Get-QuickHelp -Cmd $Command
}

跨平台通用脚本(Python)

#!/usr/bin/env python3
"""
跨平台帮助获取器
"""
import sys
import subprocess
import importlib
import pkgutil
class UniversalHelp:
    def __init__(self):
        self.platform = sys.platform
    def get_shell_help(self, command):
        """获取 Shell 命令帮助"""
        try:
            # 尝试多种帮助方式
            methods = [
                ([command, '--help'], '--help'),
                ([command, '-h'], '-h'),
                (['man', command], 'man'),
                (['info', command], 'info')
            ]
            for cmd, method in methods:
                try:
                    result = subprocess.run(
                        cmd, 
                        capture_output=True, 
                        text=True,
                        timeout=5
                    )
                    if result.returncode == 0:
                        output = result.stdout or result.stderr
                        return f"▶️ 方法: {method}\n{output[:1000]}"
                except:
                    continue
        except Exception as e:
            return f"错误: {e}"
        return None
    def get_python_help(self, obj_name):
        """获取 Python 对象帮助"""
        try:
            parts = obj_name.split('.')
            module_name = parts[0]
            obj_path = '.'.join(parts[1:])
            module = importlib.import_module(module_name)
            obj = module
            for attr in parts[1:]:
                obj = getattr(obj, attr)
            return help(obj)
        except Exception as e:
            return f"Python 帮助错误: {e}"
    def get_help(self, target):
        """主入口"""
        print(f"\n🎯 目标: {target}")
        print("=" * 40)
        # 尝试 Python 帮助
        py_help = self.get_python_help(target)
        if py_help:
            return
        # 尝试系统命令帮助
        cmd_help = self.get_shell_help(target)
        if cmd_help:
            print(cmd_help)
            return
        print("❌ 未找到帮助文档")
if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("用法: python help_getter.py <目标>")
        sys.exit(1)
    helper = UniversalHelp()
    helper.get_help(sys.argv[1])

快速使用示例

保存脚本后,使用别名快速调用:

# Linux/Mac
alias qhelp='bash script_help.sh'
# Windows PowerShell
Set-Alias qhelp .\quick_help.ps1
# Python 版本
alias pyhelp='python3 universal_help.py'

这些脚本能帮你快速获取:

  • 命令行的 --help 输出
  • man 页面
  • Python 模块文档
  • PowerShell 帮助
  • 在线文档链接

选择适合你场景的脚本即可!

抱歉,评论功能暂时关闭!