1

我正在使用 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 

它不应该抱怨上述位置论点。

这在我目前的实施中可行吗?

4

1 回答 1

3

您很可能需要自己实施此检查。将两个参数(位置和 -f)设为可选(required=False 和 nargs="*"),然后实现您的自定义检查并使用 ArgumentParser 的错误方法。为了让用户更容易在帮助字符串中提及正确的用法。

像这样的东西:

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')
于 2013-05-13T07:52:59.333 回答