我想对myprog工作进行这些调用,而不是其他人.
$ python3 myprog.py -i infile -o outfile
$ python3 myprog.py -o outfile
$ python3 myprog.py -o
$ python3 myprog.py
Run Code Online (Sandbox Code Playgroud)
特别是我想指定infile而不是outfile是非法的.
在第三种情况下,假定outfile的默认名称为"out.json".在第二种,第三种和第四种情况下,假定输入文件的默认名称为"file.n.json",其中n是整数版本号.在第四种情况下,输出文件将是"file.n + 1.json",其中n + 1是比输入文件上的版本号大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")
Run Code Online (Sandbox Code Playgroud)
问题是,当我跑
$ python3 myprog.py -i infile.json
Run Code Online (Sandbox Code Playgroud)
而不是我希望的解析器错误,我得到:
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
Run Code Online (Sandbox Code Playgroud)
...这表明,即使命令行上没有"-o",它也表现得好像有.
mhr*_*che 16
作为所选答案的附加内容:
在-o不指定文件的情况下运行的选项可以const结合使用来完成nargs='?'.
来自文档:
当使用选项字符串(如-f或--foo)和nargs ='?'调用add_argument()时.这将创建一个可选参数,后跟零个或一个命令行参数.解析命令行时,如果遇到选项字符串,后面没有命令行参数,则会假定const的值.有关示例,请参阅nargs说明.
Ben*_*dee 13
您为outfile指定了默认参数.
parser.add_argument('-o', '--outfile', nargs='?', type=argparse.FileType('w'), default='out.json', help='output file, in JSON format')
Run Code Online (Sandbox Code Playgroud)
如果-o未在命令行中指定该选项,则arg解析器将插入默认参数.
将其更改为:
parser.add_argument('-o', '--outfile', nargs='?', type=argparse.FileType('w'), help='output file, in JSON format')
Run Code Online (Sandbox Code Playgroud)
事情应该像你期望的那样工作.
如果您希望能够在-o没有文件名的情况下指定,则可能需要以下内容:
out_file = args.out if args.out is not None else 'json.out'
如果指定没有参数,我不确定相关参数是否为None或''(即空字符串)-o- 我怀疑它是None,但我不确定.你必须测试它才能确定.
如果没有argparse的额外逻辑,我不知道如何做到这一点.
| 归档时间: |
|
| 查看次数: |
26147 次 |
| 最近记录: |