使用命令行中的另一个参数覆盖位置参数和可选参数(argparse python模块)

使用命令行中的另一个参数覆盖位置参数和可选参数(argparse python模块),python,argparse,Python,Argparse,我使用argparser来解析命令行参数 现在,我有点像 ./script.py 1112323 0 --salary 100000 -- age 34 这里前两个是位置参数,其余是可选的 现在,我想有一个特性,当用户在命令行中输入一个文件名时,它应该覆盖上面的参数,并从文件头获取参数。我指的是当用户给出类似的东西时 id|sequence|age|name|........... (header of the file with first two cols as positional

我使用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 
它不应该抱怨上述位置参数


这在我当前的实施中是否可行?

您很可能需要自己实施此检查。使两个参数(positional和-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')