我正在使用argparser解析命令行参数。
现在,我有类似
./script.py 1112323 0 --salary 100000 -- age 34
这里的前两个是位置参数,其余的是可选的。
现在,我想拥有一个功能,以便当用户在命令行中输入文件名作为输入时,它应该覆盖以上这些参数,并从文件头获取参数。当用户给出类似的信息时
id|sequence|age|name|........... (header of the file with first two cols as positional arguments and rest positional)
在命令行中给出:
./script.py -f filename
它不应抱怨上述立场论点。
在我当前的实现中这可行吗?
最佳答案
您很可能需要自己实施此检查。使两个参数(位置和-f)都是可选的(required = False和nargs =“ *”),然后实现自定义检查并使用ArgumentParser的error方法。为了使用户更容易在帮助字符串中提及正确的用法。
像这样:
parser = ArgumentParser()
parser.add_argument("positional", nargs="*", help="If you don't provide positional arguments you need use -f")
parser.add_argument("-f", "--file", required=False, help="...")
args = parser.parse_args()
if not args.file and not args.positional:
parser.error('You must use either -f or positional argument')
关于python - 在命令行(argparse python模块)中用另一个参数覆盖位置参数和可选参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16516745/