0

How can I have two positional arguments, passed to a program via command line, where each argument is a list of files of variable length? I'm currently using argparse to get the arguments.

I understand you can have something similar with optional, named arguments but can you do it with positional arguments where there isn't a label (--arg) to delineate where one argument stops and the next begins?

The different files will have different file extensions, if that helps.

chrispbio
  • 39
  • 7
  • 1
    I think this might help: https://stackoverflow.com/a/15753721/9742036 EDIT: Sorry just realised you specified variable length. I don't think this is possible exactly as you've phrased it as there's no way argparse can tell when a list has ended if you don't tell it, either with a label, or by specifying the number of inputs. You might be better off taking the input as one list and manually sorting based on file extension. – Andrew McDowell Nov 05 '18 at 15:29

1 Answers1

2

If each group of files has its own file extension, then the arguments are already delineated. You can just have the argument parser put the arguments into one long list and separate them later.

parser.add_argument('filenames', nargs='*')


def getByExtension(lst, ext):
  return [f for f in lst if f.endswith(ext)]


args = parser.parse_args()

pyFiles = getByExtension(args.filenames, '.py')
scmFiles = getByExtension(args.filenames, '.scm')

Note that the user does not have to keep the arguments in any particular order for this to work, since the list comprehension doesn't care.

luther
  • 5,195
  • 1
  • 14
  • 24