我正在编写一个接受如下形式参数的程序。
SYNOPSIS
pdf_form.py <input PDF file | - | PROMPT> [ <operation> <operation arguments> ]
[ output <output filename | - | PROMPT> ] [ flatten ]
Where:
<operation> may be empty, or: [generate_fdf | fill_form |dump_data | dump_data_fields ]
OPTIONS
--help, -h
show summary of options.
<input PDF files | - | PROMPT>
An input PDF file. Use - to pass a single PDF into pdftk via stdin.
[<operation> <operation arguments>]
Available operations are:
generate_fdf,fill_form, dump_data,dump_data_fields
Some operations takes additional arguments, described below.
generate_fdf
Reads a single, input PDF file and generates an FDF file suitable for fill_form out of it
to the given output filename or (if no output is given) to stdout. Does not create a new PDF.
fill_form <FDF data filename | - | PROMPT>
Fills the input PDF's form fields with the data from an FDF file, or stdin.
Enter the data filename after fill_form, or use - to pass the data via stdin, like so:
./pdf_form.py form.pdf fill_form data.fdf output form.filled.pdf
After filling a form, the form fields remain interactive unless flatten is used.
flatten merges the form fields with the PDF pages. You can also use flatten alone, as shown:
./pdf_form.py form.pdf fill_form data.fdf output out.pdf flatten
or:
./pdf_form.py form.filled.pdf output out.pdf flatten
dump_data
Reads a single, input PDF file and reports various statistics, to the given output filename or (if no output is given).
dump_data_fields
Reads a single, input PDF file and reports form field statistics to the given output filename
[flatten]
Use this option to merge an input PDF's interactive form fields and their data with the PDF's pages.
我目前正在使用以下(混乱)代码解析这些选项
def parse(arg):
""" Parses commandline arguments. """
#checking that request is valid
if len(arg) == 1:
raise ValueError(info())
if arg[1] in ('-h', '--help'):
print(info(verbose=True))
return
if len(arg) == 2:
raise ValueError(info())
path = arg[1]
if path == 'PROMPT':
path = input('Please enter a filename for an input document:')
func = arg[2]
if func == 'fill_form':
fdf = arg[3]
if len(arg) > 5 and arg[4] == 'output':
out = arg[5]
else:
out = '-'
else:
fdf = None
if len(arg) > 4 and arg[3] == 'output':
out = arg[4]
else:
out = '-'
if out == 'PROMPT':
out = input('Output file: ')
flatten = 'flatten' in arg
return path, func, fdf, out, flatten
是否有更好的方法使用argparse或docopt来做到这一点?
一个参数可以是
parser.add_argument('-o','--output', default='-')
和
if args.output in ['PROMPT']:
... input...
:
parser.add_argument('--flatten', action='store_true')
parser.add_argument('--fill_form', dest='ftd')
parser.add_argument('--path')
if args.path in ['PROMPT']:
args.path = input...