1

I'm writing a differ. The command line needs to handle two files - left and right. I would like the synapsis to be like this:

differ.py [-f] FILE1 [[-t] FILE2]

WHERE -f is the option that accepts FILE1, -t accepts FILE2. FILE1 is mandatory, FILE2 can be read from stdin or real file. I would like it to be used like this:

differ.py myfile1
differ.py myfile1 myfile2
differ.py myfile1 -t myfile2
differ.py -f myfile1
differ.py -f myfile1 myfile2
differ.py -f myfile1 -t myfile2

Is it possible with argparse module? If so, then how? Thanks in advance.

Endrju
  • 2,354
  • 16
  • 23
  • 1
    "WHERE -f is the option that accepts FILE1" - that doesn't make sense. Is `FILE1` a positional argument or an option value? It can't be both. – user2357112 May 31 '20 at 11:21
  • if `FILE1` is mandatory argument why to parse it and declare it as optional argument? did you read the argparse module [argparse_link](https://docs.python.org/2/library/argparse.html?highlight=argparse#module-argparse)? – Adam May 31 '20 at 11:22
  • @Adam it's not an optional argument. It's mandatory, but I'd prefer `-f` string to be optional. – Endrju May 31 '20 at 11:28
  • Possble, maybe, but awkward. What's the point to using these '-t' and '-f' flags? They don't add any information, do they? – hpaulj May 31 '20 at 16:16
  • What happens if someone does `differ.py -t myfile2 myfile1`, or `differ.py myfile2 -f myfile1`? – user2357112 May 31 '20 at 21:00
  • Thanks for all the input, I'll reconsider and redesign it taking your valuable info into account. – Endrju Jun 01 '20 at 19:18

1 Answers1

1

This is not possible through argparse. It goes against too much of the design. An argument can't be both a positional argument and an option value, and which positional argument a positional argument is doesn't depend on the presence or position of options. You can't even work around any of this with mutually exclusive groups, because a positional argument can't be part of such a group. The help formatter isn't designed for any of this, either.

Even if you moved all the validation and help formatting out of argparse and into your own code, you'd be overriding so much and getting so little out of argparse that it'd be easier to just parse the command line manually.

If this is really the interface you want, it'll be easiest to parse sys.argv manually.

user2357112
  • 260,549
  • 28
  • 431
  • 505