import ArgumentParser
parser = ArgumentParser(description="Tool to keep archiving tar files")
parser.add_argument("-a", "--action", dest="action", choices=("start", "stop", "list"), help="start/stop/list the directories to be monitored", default="list", required=True)
parser.add_argument("-t", "--type", dest="type", choices=("a", "b"), help="Type of spooler job", default=None)
parser.add_argument("-p", "--path", dest="path", help="Absolute path of the directory to be monitored", default=None)
parser.add_argument("-c", "--codeline", dest="codeline", choices=("x","y","z"), default=None, required=True)
parser.add_argument("-r", "--release", dest="release", help="Directory path gets assigned automatically based on the release", default=None)
args = parser.parse_args()
在上面的代码中,如果动作被指定为start/stop,则type和path/release中的一个是必需的输入。有没有办法在add_argument方法本身做到这一点?如何在python中对命令行参数进行分组?
附加信息:
如果该操作以“列表”形式给出,则不需要其他选项。例如,“script.py -a列表”应该工作。 只有当动作以开始/停止的形式给出时,其他选项才是必需的。例如,“script.py -a start”应该抛出错误。 “script.py -a启动-TA -p/tmp目录-CX”或“script.py -a开始-tb -r RR -cy”应该工作
您可能需要使用subparser:http://docs.python.org/2/library/argparse.html#sub-commands。 – sberry