【问题标题】:How to add a help command to a .exe program?如何向 .exe 程序添加帮助命令?
【发布时间】:2022-12-18 11:47:04
【问题描述】:

我刚刚用 Python 编写完代码并将其转换为 .exe 文件,作为附加组件,我想添加一个 help 命令以在命令提示符下显示我的程序功能的快速说明。我是否必须在我的 .py 文件中添加参数,或者我是否需要为此参数创建一个 .ini/.bat 文件?

我想要发生的事情:在 CMD 上我的 .exe 目录的路径中,键入 help 命令以显示我的程序执行的文本。

【问题讨论】:

  • 我会说 myprogr.exe /?myprog --help 会更有意义,而不是试图覆盖(或以某种方式重用)本机 help.exe 如果您碰巧从所需路径运行它。如果需要,在没有任何参数的情况下运行 myprog.exe 可以默认为 myprog.exe /?

标签: python cmd exe


【解决方案1】:
# Import the argparse module to create a command line argument parser
import argparse

# Create a new ArgumentParser object
parser = argparse.ArgumentParser()

# Add a help argument to the parser
parser.add_argument('--help', action='store_true', help='Show a brief description of the program')

# Parse the command line arguments
args = parser.parse_args()

# Check if the help argument was provided
if args.help:
    # Print a brief description of the program
    print('This program does XYZ')

# Your existing code goes here...

然后,当你运行.exe文件时,你可以传递--help参数来查看程序的简要描述。例如:

C:path	omyprogram.exe --help

【讨论】:

    【解决方案2】:

    Raya 的回答很好,但代码可以更短。您不需要向解析器添加特定的帮助选项。如果您使用描述参数初始化解析器,这将默认添加,例如,

    import argparse
    
    parser = argparse.ArgumentParser(description="My code does great stuff")
    args = parser.parse_args()
    

    然后运行

    myprogram.exe --help
    

    会给:

    My code does great stuff
    
    optional arguments:
      -h, --help  show this help message and exit
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-27
      • 1970-01-01
      • 1970-01-01
      • 2011-01-12
      • 2021-09-09
      • 2019-11-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多