argparse:位置参数之间的可选参数

如何解决argparse:位置参数之间的可选参数

我想模拟大多数命令行实用程序的行为,可以在命令行中的任意位置放置可选参数,包括 间的位置参数,例如本mkdir示例:

mkdir before --mode 077 after

在这种情况下,我们知道--mode正好接受1个参数,因此beforeafter都被视为位置参数。可以将可选部分--mode 077放在命令行的任意位置

但是,对于argparse,以下代码不适用于该示例:

# mkdir.py
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--mode',nargs=1)
parser.add_argument('dirs',nargs='*')
args = parser.parse_args()

运行./mkdir.py before --mode 077 after会导致:

mkdir.py: error: unrecognized arguments: after

如何让argparse接受位置参数之间的可选参数(具有已知的固定数量的参数)?

解决方法

Python 3.7开始,看来argparse现在支持这种Unix风格的解析:

混合解析

ArgumentParser.parse_intermixed_args(args=None,namespace=None)

许多Unix命令允许用户将可选参数与位置参数混合在一起。 parse_intermixed_args()parse_known_intermixed_args()方法支持这种解析样式。

有一个警告,但是对于“简单”选项,它不会影响它们:

这些解析器不支持所有的argparse功能,如果使用了不受支持的功能,则会引发异常。特别是,不支持子解析器argparse.REMAINDER以及同时包含可选和位置的互斥组。

(我花了1个小时试图理解为什么Python argparse文档中的示例似乎没有包含该示例,但我偶然发现了一个不相关的问题,在注释中包含对该“混合”函数的提及,我无法再次找到对其进行正确引用。)

,

我对argparse不熟悉,所以我会编写自己的代码来处理参数。

import sys

#the first argument is the name of the program,so we skip that
args = sys.argv[1:]
#just for debugging purposes:
argsLen = len(args)
print(args,argsLen)

#Create a list that will contain all of the indeces that you will have parsed through
completedIndeces = []
i = 0

#add the index to the completed indeces list.
def goToNextIndex(j):
    global i
    completedIndeces.append(j)
    i += 1

def main():
    global i
    ###core logic example
    #Go through each item in args and decide what to do based on the arugments passed in
    for argu in args:
        if i in completedIndeces:
            print("breaking out")
            #increment i and break out of the current loop
            i += 1
            # If the indeces list has the index value then nothing else is done.
            pass 
        elif argu == "joe":
            print("did work with joe")
            goToNextIndex(i)
        elif argu == "sam":
            print("did work with sam")
            goToNextIndex(i)
        elif argu == "school":
            print("going to school")
            goToNextIndex(i)

            # If the argument has other arguments after it that are associated with it 
            # then add those indeces also to the completed indeces list. 
    
            #take in the argument following school
            nextArg = i
            #Do some work with the next argument
            schoolName = args[nextArg]
            print(f"You're going to the school called {schoolName}")
            #make sure to skip the next argument as it has already been handled
            completedIndeces.append(nextArg)
        else:
            print(f"Error the following argument is invalid: {argu}")
            goToNextIndex(i)


    print(f"Value of i: {i}")
    print(f"completed indeces List: {completedIndeces}")

main()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?