这个场景适合吗?
模块 B:
import argparse
parser = argparse....
def main(args):
....
if __name__ == '__main__':
args = parser.parse_args()
main(args)
模块 A
import argparse
import B
parser = argparse....
# define arguments that A needs to use
if _name__=='__main__':
args,rest = parser.parse_known_args()
# use args
# rest - argument strings that A could not process
argsB = B.parse_args(rest)
# 'rest' does not have the strings that A used;
# but could also use
# argsB = B.parse_known_args() # using sys.argv; ignore what it does not recognize
# or even
# argsB = B.parse_known_args(rest)
B.main(argsB)
备用A
import argparse
import B
parser = argparse.ArgumentParser(parents=[B.parser], add_help=False)
# B.parser probably already defines -h
# add arguments that A needs to use
if _name__=='__main__':
args = parser.parse_args()
# use args that A needs
B.main(args)
在一种情况下,每个解析器只处理它识别的字符串。在另一个 A.parser 处理所有事情,使用“父母”参数来“学习”B.parser 识别的内容。