4

I have to write a program with this command line :

demo.py [-h] -f FILENAME [-o]

The filename is mandatory and means that the file we be appended to. The -o flag means that the file will overwritten.

This argparse code almost works :

import argparse

parser = argparse.ArgumentParser(description='A foo that bars')

parser.add_argument("-f",
                  "--file", dest="filename", required=True,
                  type=argparse.FileType('a+'),
                  help="The output file (append mode, see --overwrite).")

parser.add_argument("-o",
                  "--overwrite", dest="overwrite",
                  action='store_true',
                  help="Will overwrite the filename if it exists")

args = parser.parse_args()

if args.overwrite:
    args.filename.truncate(0)

print >> args.filename, 'Hello, World!'

But if I specify - (stdout) as a filename, I get this error :

error: argument -f/--file: invalid FileType('a+') value: '-'

I tried a or r+, I get the same error. I am using Python 2.7 on Windows, but it must also work on Linux. The command line cannot change for legacy support.

How can I keep argparse built-in support for stdout shorthand, but support an overwrite feature ?

ixe013
  • 9,559
  • 3
  • 46
  • 77

1 Answers1

5

argparse.FileType.__call__ contains this code:

    if string == '-':
        if 'r' in self._mode:
            return _sys.stdin
        elif 'w' in self._mode:
            return _sys.stdout
        else:
            msg = _('argument "-" with mode %r') % self._mode
            raise ValueError(msg)

So, if self._mode is 'a+', Python raises a ValueError. You could work around this by subclassing argparse.FileType:

import argparse
import sys as _sys

class MyFileType(argparse.FileType):

    def __call__(self, string):
        # the special argument "-" means sys.std{in,out}
        if string == '-':
            if 'r' in self._mode:
                return _sys.stdin
            elif any(m in self._mode for m in 'wa'):
                return _sys.stdout
            else:
                msg = _('argument "-" with mode %r') % self._mode
                raise ValueError(msg)

        # all other arguments are used as file names
        try:
            return open(string, self._mode, self._bufsize)
        except IOError as e:
            message = _("can't open '%s': %s")
            raise ArgumentTypeError(message % (string, e))


def parse_options():
    parser = argparse.ArgumentParser(description='A foo that bars')

    parser.add_argument("-f",
                      "--file", dest="filename", required=True,
                      type=MyFileType('a+'),
                      help="The output file (append mode, see --overwrite).")

    parser.add_argument("-o",
                      "--overwrite", dest="overwrite",
                      action='store_true',
                      help="Will overwrite the filename if it exists")

    args = parser.parse_args()

    if args.overwrite:
        args.filename.truncate(0)
    return args

args = parse_options()
print >> args.filename, 'Hello, World!'
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677