Python argparse : get an argument without parsing

标签 python arguments argparse

我正在尝试编写一个简单的 python 脚本,该脚本将使用命名约定重命名目录中的文件。为此,我需要目录的路径和要处理的文件数量。默认情况下,我希望脚本重命名目录中的所有文件。

import os
import sys
import shutil
import argparse

parser = argparse.ArgumentParser(description='Rename files in the directory, using naming conventions')
parser.add_argument('name', help='first part of a new name')
parser.add_argument('--dir', default=os.getcwd(), help='directory containing files')
parser.add_argument('--num', type=int, default = len([file for file in os.listdir(parser.parse_args().dir)]),
                        help='number of files to rename')

args = parser.parse_args()

这是仅“-h”参数的输出:

usage: rename.py [-h] [--dir DIR] name

Rename files in the directory, using naming conventions

positional arguments:
  name        first part of a new name

optional arguments:
  -h, --help  show this help message and exit
  --dir DIR   directory containing files

在我看来,由于parser.parse_args().dir,最后一个参数没有被处理。

有没有办法在不解析前一个参数的情况下获取它的信息?

最佳答案

Is there a way to get information about the previous argument without parsing it?

没有。至少不是您正在搜索的信息。要知道为其中一个参数指定的值是什么,您需要解析这些参数。

实现您想要的默认行为的方法是通过一个标志值,意思是“处理全部”。例如:

parser.add_argument('--num', type=int, default=None),
                        help='number of files to rename')

# then in your code, after you parse the arguments:

if args.num is not None:
  # process just num
else:
  # process all the files

关于Python argparse : get an argument without parsing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60000965/

相关文章:

python - 如何使用 OpenCV 去除图像上的蓝色背景颜色?

python - 为什么通过 python 默认变量初始化变量会跨对象实例化保持状态?

c - C 中的标志顺序

python - argparse 选择允许值的结构

python - argparse 和 optparse 的替代子命令

python - 调试时模拟 argparse 命令行参数输入

python - 打开目录中的每个文本文件,然后替换每个文本文件中的特定行

python - Django FormView 响应

python - 字符串转换时间

c++ - 类成员值的合法或错误成员使用?