Arden
Arden

Reputation: 15

Python argparse: get an argument without parsing

I am trying to write a simple python script that will rename files in the directory, using naming conventions. To do this, I need a path to the directory and the number of files to process. By default, I want the script to rename all files in the directory.

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()

And here is an output for just '-h' argument:

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

It seems to me that the last argument is not being processed due to parser.parse_args().dir.

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

Upvotes: 1

Views: 1163

Answers (1)

GPhilo
GPhilo

Reputation: 19123

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

No. Not the info you're searching for, at least. To know what the value given for one of the arguments is, you need to parse the arguments.

The way to implement the default behavior you want is via a flag value meaning "process them all". For example:

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

Upvotes: 1

Related Questions