如何将子部分用于可选的位置参数?

发布于 2025-02-10 13:19:42 字数 922 浏览 0 评论 0 原文

我刚刚开始使用 argprase ,并且具有以下示例 main.py

import os
import numpy
import argparse

def main():
    parser = argparse.ArgumentParser() 
    parser.add_argument('-C','--Chk',type=str, help='Choose arg')
    args = vars(parser.parse_args())
 
    if args['Chk'] == 'compo1':
        print('This is test1')
    elif args['Chk'] == 'compo2':
        print('This is test2')
       
if __name__=='__main__':
    main()

如果我使用 python3 main.py.py -c compo1 我得到所需的结果,即,这是test1 。现在,如果调用 -c compo1 ,我想添加附加参数。例如 python main.py -c compa1 -d 其中, -d 执行一个任务,例如。

This is test1 #output for -C compo1
This is sub task from test1 #2nd output when -d is called 

另外,我希望 -d 也是 compa2 时的标志,但随后输出应不同并且指定。

谁能建议如何在ArgParse库中获得可选位置论点的其他论点?并且子部分可以用于可选参数和相同的命令线标志吗?

I have just started working with argprase, and have the following example main.py which has optional arguments

import os
import numpy
import argparse

def main():
    parser = argparse.ArgumentParser() 
    parser.add_argument('-C','--Chk',type=str, help='Choose arg')
    args = vars(parser.parse_args())
 
    if args['Chk'] == 'compo1':
        print('This is test1')
    elif args['Chk'] == 'compo2':
        print('This is test2')
       
if __name__=='__main__':
    main()

If I use python3 main.py -C compo1 I get the desired result, i.e, This is test1. Now, I would like to add addtional arguments if -C compo1 is called. For example python main.py -C compa1 -d where, -d performs a task, for eg.

This is test1 #output for -C compo1
This is sub task from test1 #2nd output when -d is called 

Also, I would like -d to be the flag when compa2 is called too, but then the output should be different and as specified.

Can anyone suggest how to get additional arguments for optional positional arguments in argparse library ? and can subparses be used for optional arguments and with the same command line flag ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

稀香 2025-02-17 13:19:42

因此,不幸的是,我能告诉我的答案是否定的。 ArgParse模块无法区分您想区分的订单。但是,我确实在

中,

我为您的设置编码了以下实现方案:

import argparse, sys
parser = argparse.ArgumentParser(description="Usage: [-C CHK -d]")
parser.add_argument('-C','--Chk', type=str, help='Choose arg')
parser.add_argument('-d', default=False, action="store_true", help='d bool of CHK option')
args = parser.parse_args()

def get_arg_index(args: list, name: str):
    return next((i for i, v in enumerate(args) if v.startswith(name)), None)

if args.Chk:
    if args.d:
        # if chk was called with 'd' submodule, check ordering is correct.
        idx_Chk = (get_arg_index(sys.argv, "-C") if "-C" in sys.argv else get_arg_index(sys.argv, "--Chk"))
        idx_d = get_arg_index(sys.argv, "-d")
        assert idx_Chk + 2  == idx_d, \
            "Error. The index of the --foo and -d flags was not separated by exactly one arg. "
        parser.print_help()
        sys.exit()

由于ArgParse帮助不会显示您要鼓励的格式,我建议编写详细的 Description> Description> Description 消息以指示 -d 标志在哪里。希望这有帮助!

So the answer from what I can tell is unfortunately no. The argparse module can't distinguish between the orderings which you would like to distinguish between. I did however find some decent workarounds to this issue at

Find the order of arguments in argparse python3

I coded the following implementation scheme for your setup:

import argparse, sys
parser = argparse.ArgumentParser(description="Usage: [-C CHK -d]")
parser.add_argument('-C','--Chk', type=str, help='Choose arg')
parser.add_argument('-d', default=False, action="store_true", help='d bool of CHK option')
args = parser.parse_args()

def get_arg_index(args: list, name: str):
    return next((i for i, v in enumerate(args) if v.startswith(name)), None)

if args.Chk:
    if args.d:
        # if chk was called with 'd' submodule, check ordering is correct.
        idx_Chk = (get_arg_index(sys.argv, "-C") if "-C" in sys.argv else get_arg_index(sys.argv, "--Chk"))
        idx_d = get_arg_index(sys.argv, "-d")
        assert idx_Chk + 2  == idx_d, \
            "Error. The index of the --foo and -d flags was not separated by exactly one arg. "
        parser.print_help()
        sys.exit()

Since the argparse help won't display the formatting that you're trying to encourage, I'd recommend writing a detailed description message to indicate where the -d flags go. Hope this helps!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文