Python argparse:在不进行解析的情况下获取参数

2024-04-23 17:26:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编写一个简单的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,最后一个参数没有被处理

有没有一种方法可以在不解析前一个参数的情况下获取有关该参数的信息


Tags: 文件nameinimport目录addparser参数
1条回答
网友
1楼 · 发布于 2024-04-23 17:26:33

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

相关问题 更多 >