1

I am using argparse for command line arguments, where one argument is one or more .csv files:

parser = argparse.ArgumentParser(description='...')
parser.add_argument('csv', type=str, nargs='+', help='.csv file(s)'))
parser.add_argument('days', type=int, help='Number of days'))

args = parser.parse_args()

print(args.csv)

When running $ python Filename.py csv Filename.csv days 30, args.csv is ['csv', 'Filename.csv', 'days'], but I don't want to be capturing the csv and days arguments which surround the input csv files.

  • 2
    When you add arguments without the `--` prefix, they become positional arguments. You don't need to write "csv" nor "days" in the command call, their values are defined by their position. `python Filename.py Filename.csv 30` will work as you expect it to – GPhilo Jul 29 '20 at 10:05
  • You have two arguments, the first captures all except the last one. That's expected. What do you actually want to achieve? – a_guest Jul 29 '20 at 10:06
  • @GPhilo explained it @a_guest I didn't realise that I didn't need to write ````csv```` and ````days```` –  Jul 29 '20 at 10:08

1 Answers1

0

You can use

import argparse
parser = argparse.ArgumentParser(description='...')
parser.add_argument("csv", type=str, nargs='+', help='.csv file(s)')
parser.add_argument("days", type=int, help='Number of days')

args = parser.parse_args()

print(args.csv)

Invoked with e.g. python your_script.py test.csv 100 this yields

['test.csv']

Note that you do not need to encapsulate parser.add_argument(...) twice (as you had in your code).

Jan
  • 42,290
  • 8
  • 54
  • 79
  • I have edited my question, as I had erroneously copied over my code, I had not made the ````parser.add_argument(parser.add_argument```` error in my original code. The answer is correct but I feel that repeating my code is a bit superfluous? Rather than just adding a comment –  Jul 29 '20 at 10:11