【发布时间】:2015-01-28 00:17:12
【问题描述】:
我想在 Python 中使用argparse 来声明参数如下:
./get_efms_by_ids [-h] [-v] [inputfile [1 3 4 9] [-c 11..18] [20 25 40]]
在这种情况下我想做的是:
如果使用inputfile,则可以采用两种类型的可选参数:1 3 4 9 或c 11..18 或两者。如果我不输入inputfile,则必须缺少可选参数。
例如: 我可以给你看一些命令行用法的例子:
./get_efms_by_ids Vacf.txt // default: get 1 or 10 first lines in Vacf.txt
./get_efms_by_ids Vacf.txt 1 3 4 9 // get the lines that indexes: 1 3 4 9 in Vacf.txt
./get_efms_by_ids Vacf.txt c 11..18 22 25 29 // get the lines that indexes are from 11 to 18, then the lines 22, 25, 29
./get_efms_by_ids c 11.. 18 // shows a readable error message
./get_efms_by_ids 1 3 4 9 // shows a readable error message
可以使用args='?' 或args='*',如下例所示:
parser = argparse.ArgumentParser(description='Selecting some Elementary Flux Modes by indexes.',version='1.0')
parser.add_argument('efm_matrix_file', type=file, help='give the name of the efms matrix file')
parser.add_argument('ids', nargs='?', help='give the indexes of the chosen efms')
parser.add_argument('-i','--indexes',nargs='*', help='give the begin and start indexes of the chosen efms')
但结果并不符合本文开头提出的目的。
任何帮助将不胜感激。
【问题讨论】:
-
不清楚你想要什么。我的猜测是
inputfile是可选的,但如果它在那里,你不想要以下任何一个、一些或全部,按顺序:1、3、4、9 之一;-c一个参数在 11 和 18 之间;和 20、25、40 之一? -
@chepner:
inputfile是可选的。实际上,我想知道inputfile没有使用,其余可选参数将不存在。换句话说,它们依赖于inputfile。我使用-c 11..18来获取索引范围为 11 到 18 的所有行。如果使用 1、3、4、9 等,我想获取各个元素。 -
参数组不影响解析;他们只是在帮助信息中组织论据。
-
type=file是错误的。type采用将字符串转换为其他内容的函数。我建议接受一个文件名(字符串)并稍后打开它。