python - 有没有办法使用 argparse 模块输入以 '-' 符号开头的字符串作为命令行参数? (不使用标志)

标签 python command-line command-line-interface argparse

所以我有这个代码

# driver code    
if __name__ == "__main__":

    # parse command line arguments 
    parser = argparse.ArgumentParser()
    parser.add_argument("InputDataFile", help="Enter the name of CSV file with .csv extention",type=str)
    parser.add_argument("Weights", nargs=1, help="Enter the weight vector comma separated" ,type=str)
    parser.add_argument("Impacts", nargs=1, help="Enter the impact vector comma separated",type=str)
    args = parser.parse_args()


    main(vars(args))

我想输入一个字符串

python top2.py data.csv "0,1,1,1" "-,+,+,+"

但我收到输入错误:

usage: top2.py [-h] InputDataFile Weights Impacts
top2.py: error: the following arguments are required: Impacts

如果输入字符串的第一个字符是“+”号,中间有一个“-”(如“+、-、+”),则代码可以正常工作。但如果第一个字符是“-”,我会收到上述错误。 我猜测解析器将“-”连字符作为另一个标志及其参数的开头。

我在网上找不到任何相关资料,请帮忙。

并且按照上面给出的方式输入字符串很重要,因此不能更改输入格式。

编辑:如果我输入字符串为“-,+,+,+”或在字符串中的任意位置添加空格,则代码运行良好。

最佳答案

您可以简单地在命令行中添加一个单独的 -- 来指示“这是选项的结尾”,如下所示:

python top2.py -- data.csv "0,1,1,1" "-,+,+,+"

-- 之后的所有内容都被解析为位置参数而不是选项。

关于python - 有没有办法使用 argparse 模块输入以 '-' 符号开头的字符串作为命令行参数? (不使用标志),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59823164/

相关文章:

python - 如何沿路径移动补丁?

python - 无法正常运行 while 循环

c++ - 使用命令行参数创建和运行文件

c# - 如何 : Execute command line in C#, 获取 STD OUT 结果

postgresql - Postgres - 来自 CLI 的更新命令

python /pypyODBC : Row Insert Using String and NULLs

bash - 小于 if 语句中的运算符 '<' 结果为 'No such file or directory'

ssl - 您将如何通过 CLI(命令行界面)创建 SSL 自签名证书

linux - 目录统计命令行界面?

python - 如何构建多索引转换矩阵?