argparse.FileType .__ call__包含以下代码:
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)
因此,如果self._mode为’a’,Python将引发ValueError.
您可以通过继承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!'