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 ?