Python argparse:获取参数而不进行解析

问题描述 投票:0回答:1

我正在尝试编写一个简单的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,最后一个参数未得到处理。

是否有一种无需解析就可以获得有关前一个参数的信息?

python arguments argparse
1个回答
0
投票

是否有一种无需解析就可以获得有关前一个参数的信息?

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

实现所需默认行为的方法是通过标志值表示”全部处理”。例如:

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
© www.soinside.com 2019 - 2024. All rights reserved.