title: how to make argument optional in python argparse
body: <p>I would like to make these invocations of myprog work, and no others.</p>
  
  <pre><code>$ python3 myprog.py -i infile -o outfile
  $ python3 myprog.py -o outfile
  $ python3 myprog.py -o
  $ python3 myprog.py 
  </code></pre>
  
  <p>In particular I want to make it illegal to specify the infile but not the outfile.</p>
  
  <p>In the third case, a default name for the outfile is assumed, "out.json." In the second, third and fourth cases, a default name for the input file is assumed, "file.n.json", where n is an integer version number. In the fourth case the output file would be "file.n+1.json" where n+1 is a version number one larger than the one on the input file. The relevant section of my code is:</p>
  
  <pre><code>import argparse
  
  parser = argparse.ArgumentParser(description="first python version")
  parser.add_argument('-i', '--infile', nargs=1, type=argparse.FileType('r'), help='input file, in JSON format')
  parser.add_argument('-o', '--outfile', nargs='?', type=argparse.FileType('w'), default='out.json', help='output file, in JSON format')
  
  args = parser.parse_args()
  
  print("Here's what we saw on the command line: ")
  print("args.infile",args.infile)
  print("args.outfile",args.outfile)
  
  if args.infile and not args.outfile:
      parser.error("dont specify an infile without specifying an outfile")
  elif not args.infile:
      print("fetching infile")
  else: # neither was specified on the command line
      print("fetching both infile and outfile")
  </code></pre>
  
  <p>Problem is, when I run </p>
  
  <pre><code>$ python3 myprog.py -i infile.json
  </code></pre>
  
  <p>instead of the parser error I hoped for, I get:</p>
  
  <pre><code>Here's what we saw on the command line: 
  args.infile [&lt;_io.TextIOWrapper name='infile.json' mode='r' encoding='UTF-8'&gt;]
  args.outfile &lt;_io.TextIOWrapper name='out.json' mode='w' encoding='UTF-8'&gt;
  fetching both infile and outfile
  </code></pre>
  
  <p>...which suggests that even though there was no "-o" on the command line it acted as if there was.</p>