【发布时间】:2013-03-23 03:54:29
【问题描述】:
我想让 myprog 的这些调用工作,而不是其他的。
$ python3 myprog.py -i infile -o outfile
$ python3 myprog.py -o outfile
$ python3 myprog.py -o
$ python3 myprog.py
我特别想让指定 infile 而不是 outfile 成为非法。
在第三种情况下,假定输出文件的默认名称为“out.json”。在第二种、第三种和第四种情况下,假定输入文件的默认名称为“file.n.json”,其中 n 是整数版本号。在第四种情况下,输出文件将是“file.n+1.json”,其中 n+1 是比输入文件上的版本大一号的版本号。我的代码的相关部分是:
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")
问题是,当我运行时
$ python3 myprog.py -i infile.json
我得到的不是我希望的解析器错误:
Here's what we saw on the command line:
args.infile [<_io.TextIOWrapper name='infile.json' mode='r' encoding='UTF-8'>]
args.outfile <_io.TextIOWrapper name='out.json' mode='w' encoding='UTF-8'>
fetching both infile and outfile
...这表明即使命令行上没有“-o”,它的行为就像有一样。
【问题讨论】:
-
第三种情况和第四种情况有什么区别? -o 代表什么?
-
第四种情况将使用默认的 infile 和 outfile 名称(特别是 file.n.json 和 file.n+1.json,即嵌入了版本号的文件)。这些与“out.json”不同,后者是“-o”选项的第三种情况。我已经修改了上面的文字以表明这一点。
-
第 4 种情况应该如何工作,因为
--input选项没有默认值?