argparse

python package: argparse

The following is a simple usage example that sums integers from the command-line and writes the result to a file::

parser = argparse.ArgumentParser(description='sum the integers at the command line')
parser.add_argument('integers', metavar='int', nargs='+', type=int, help='an integer to be summed')
parser.add_argument('--log', default=sys.stdout, type=argparse.FileType('w'),
                    help='the file where the sum should be written')
args = parser.parse_args()
args.log.write('%s' % sum(args.integers))
args.log.close()

The module contains the following public classes:
- ArgumentParser – The main entry point for command-line parsing. As the example above shows, the add_argument() method is used to populate the parser with actions for optional and positional arguments. Then the parse_args() method is invoked to convert the args at the command-line into an object with attributes.
- ArgumentError – The exception raised by ArgumentParser objects when there are errors with the parser’s actions. Errors raised while parsing the command-line are caught by ArgumentParser and emitted as command-line messages.
- FileType – A factory for defining types of files to be created. As the example above shows, instances of FileType are typically passed as the type= argument of add_argument() calls.
- Action – The base class for parser actions. Typically actions are selected by passing strings like ‘store_true’ or ‘append_const’ to the action= argument of add_argument(). However, for greater customization of ArgumentParser actions, subclasses of Action may be defined and passed as the action= argument.
- HelpFormatter, RawDescriptionHelpFormatter, RawTextHelpFormatter, ArgumentDefaultsHelpFormatter – Formatter classes which may be passed as the formatter_class= argument to the ArgumentParser constructor. HelpFormatter is the default, RawDescriptionHelpFormatter and RawTextHelpFormatter tell the parser not to change the formatting for help text, and ArgumentDefaultsHelpFormatter adds information about argument defaults to the help.

A simple example:

import argparse
import sys
if __name__ == "__main__":
  parser = argparse.ArgumentParser()
  parser.register("type", "bool", lambda v: v.lower() == "true")
  parser.add_argument(
      "--max_steps",
      type=int,
      default=10,
      help="Number of steps to run trainer.")
  parser.add_argument(
      "--train_batch_size",
      type=int,
      default=100,
      help="Batch size used during training.")
  parser.add_argument(
      "--learning_rate",
      type=float,
      default=0.025,
      help="Initial learning rate.")
  parser.add_argument(
      "--data_dir",
      type=str,
      default="/tmp/mnist_data",
      help="Directory for storing data")
  parser.add_argument(
      "--ui_type",
      type=str,
      default="curses",
      help="Command-line user interface type (curses | readline)")
  parser.add_argument(
      "--fake_data",
      type="bool",
      nargs="?",
      const=True,
      default=False,
      help="Use fake MNIST data for unit testing")
  parser.add_argument(
      "--debug",
      type="bool",
      nargs="?",
      const=True,
      default=False,
      help="Use debugger to track down bad values during training")
  FLAGS, unparsed = parser.parse_known_args()
[root@...]# python test.py --max_steps 100 --train_batchsize 128
### Python `argparse` 使用指南与常见问题解答 #### 什么是 `argparse` `argparse` 是 Python 标准库中的模块之一,专门用于处理命令行参数和选项。通过此模块可以轻松创建用户友好的命令行界面[^1]。 #### 项目目录结构及介绍 一个典型的使用 `argparse` 的项目的目录结构如下所示: ``` project/ │ ├── main.py # 主程序入口 ├── utils/ # 辅助函数或类的存储位置 │ └── helper.py # 提供额外的功能支持 └── README.md # 描述项目基本信息和其他相关内容 ``` 其中,`main.py` 文件通常是负责接收并解析来自终端用户的输入的地方。 #### 示例代码:控制台输入的回声效果 下面是一个简单的例子来展示如何利用 `argparse` 实现基本功能——即让用户能够传递字符串给脚本执行后返回相同的内容。 ```python # echo_example.py import argparse parser = argparse.ArgumentParser(description="Echo the input string back to user.") parser.add_argument("echo", type=str, help="String value that will be echoed.") args = parser.parse_args() print(f"Echoed String: {args.echo}") ``` 当运行上面这段代码时,你可以像这样调用它: ```bash $ python echo_example.py Hello_World Echoed String: Hello_World ``` #### 处理路径拼接的小贴士 为了避免手动编写跨平台兼容性的路径连接逻辑带来的麻烦,推荐总是采用内置方法代替硬编码方式。例如,可以用 `os.path.join()` 来安全可靠地组合文件夹名与文件名[^3]: ```python import os full_path = os.path.join('parent_dir', 'child_dir', 'file.txt') print(full_path) # 输出结果取决于当前操作系统环境变量配置情况 ``` #### 关于其他语言生态系统的对比 值得注意的是,在不同的编程环境中也存在着类似的工具服务于相似的目的。比如说,在 Java 生态圈子里就有名为 **argparse4j** 的第三方库,它的设计理念很大程度受到了原生 Python 版本的影响[^4]。然而两者之间仍然存在一定差异性需要注意区分对待。 --- ### 常见新手问题及其解决办法 #### Q1. 我遇到了版本更新后的兼容性难题怎么办? A1. 如果发现某些旧有特性不再受最新发行版的支持,则建议查阅官方发布日志寻找替代方案;同时也可以考虑锁定特定依赖项防止意外变动影响既有业务逻辑正常运作[^4]。 #### Q2. 如何添加可选参数而非强制要求用户提供全部必要字段? A2. 利用 `.add_argument()` 方法里的 `--option-name` 形式的标志位声明非必需型别的条目即可达成目标。例如: ```python parser.add_argument('--verbosity', default='low', choices=['high','medium','low'], help='Set output verbosity level.') ``` #### Q3. 支持子命令该如何操作? A3. 可以借助 `.add_subparsers()` 构建分层式指令体系架构。详情参阅下方片段示范: ```python subparsers = parser.add_subparsers(dest='command') start_parser = subparsers.add_parser('start', help='Start service operation.') stop_parser = subparsers.add_parser('stop', help='Stop running instance.') args = parser.parse_args(['start']) assert args.command == 'start' ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值