Python argparse:命令行值未为可选值初始化

如何解决Python argparse:命令行值未为可选值初始化

我有以下参数将使用 argparse 进行解析

  • input_dir(字符串:强制)
  • output_dir(字符串:强制)
  • file_path(字符串:强制)
  • supported_file_extensions(逗号分隔的字符串 - 可选)
  • ignore_tests(布尔值 - 可选)

如果分别为 supported_file_extensionsignore_tests 提供逗号分隔的字符串和字符串,那么我希望将该值设置为参数变量。我的设置如下

import sys

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument(
        'input_dir',type=str,help='Fully qualified directory for the input directory')
    parser.add_argument(
        'file_path',help='Fully  qualified path name for file')
    parser.add_argument(
       'output',help='Fully qualified output directory path')
    parser.add_argument(
        '-supported_file_extensions',nargs='?',default=None,help='optional comma separated file extensions'
    ) # Should default to False
    parser.add_argument(
        '-ignore_tests',type=bool,default=True
    ) # Should default to True if the argument is passed
    (arguments,_) = parser.parse_kNown_args(sys.argv[1:])
    print(arguments)

当我传递以下命令时

 python cloc.py -input_dir /myproject -file_path /myproject/.github/CODEOWNERS -output output.json --supported_file_extensions java,kt --ignore_tests False

我希望参数的值。--supported_file_extensions 等于 java,ktignore_tests 等于 False 但我得到以下值

Namespace(file_path='/myproject/.github/CODEOWNERS',ignore_tests=True,input_dir='/myproject',output='output.json',supported_file_extensions=None)

如果我不在命令行参数中传递 --ignored_tests,那么我希望文件认为 False。同样,当我传递 --ignored_tests 时,我希望将参数设置为 True

如果我传递 --supported_file_extensions java,kt,那么我希望将参数设置为 java,kt 作为字符串,而不是列表。

我尝试过,但没有成功。

  1. Python argparse: default value or specified value
  2. python argparse default value for optional argument
  3. Creating command lines with python (argparse)

更新 我更新了最后两个参数如下:

parser.add_argument(
        '-supported_file_extensions',help='optional comma separated file extensions'
    )
    parser.add_argument(
        '-ignore_tests',action='store_true',help='optional flag to ignore '
    )
    (arguments,_) = parser.parse_kNown_args(sys.argv[1:])
    print(arguments)

当我运行命令时

  python cloc.py -input_dir /myproject -file_path /myproject/.github/CODEOWNERS -output output.json --supported_file_extensions java,kt

输出如下

 Namespace(file_path='/myproject/.github/CODEOWNERS',ignore_tests=False,supported_file_extensions=None)

虽然 ignore_tests 的值是正确的(认为 false),但 supported_file_extensions 的值是 None,这是不正确的,因为我已经将 java,kt 作为命令行参数。

当我通过时

 python cloc.py -input_dir /myproject -file_path /myproject/.github/CODEOWNERS -output output.json --supported_file_extensions java,kt --ignore_tests 

我得到以下输出

Namespace(file_path='/myproject/.github/CODEOWNERS',supported_file_extensions=None)

解决方法

你的论点不正确。您将解析器的参数注册为 -ignore_tests,但在命令行上将其指定为 --ignore_tests — 请注意前面的破折号的数量。您也不需要为位置参数指定 -input_dir,它们什么都不做。

通常,上述两个问题都会导致您的脚本崩溃。它仍然运行的唯一原因是因为您使用了 parser.parse_known_args,它忽略了它不理解的所有参数 - 例如 --ignore_tests-input_dir

你应该运行的命令是:

python cloc.py /myproject /myproject/.github/CODEOWNERS output.json -supported_file_extensions java,kt -ignore_tests False

此外,正如许多评论中提到的,在注册参数时不要使用 type=bool。相反,使用

parser.add_argument('-ignore_tests',action='store_true')

ignore_tests 存在时,这会将 True 设置为 -ignore_tests,否则设置为 False — 无需显式指定 TrueFalse命令行。

,

我认为这是一个更好的定义:

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '--input_dir',help='Fully qualified directory for the input directory')
    parser.add_argument(
        '--file_path',help='Fully  qualified path name for file')
    parser.add_argument(
       '--output',help='Fully qualified output directory path')
    parser.add_argument(
        '--supported_file_extensions',help='optional comma separated file extensions'
    ) # only use ? if defining default and const
    parser.add_argument(
        '--ignore_tests',action='store_true'
    )
    (arguments,extras) = parser.parse_known_args()
    print(arguments)
    print(extras)

致电:

python cloc.py --input_dir /myproject --file_path /myproject/.github/CODEOWNERS --output output.json --supported_file_extensions java,kt

另一个版本:

if name == 'ma​​in': 解析器 = argparse.ArgumentParser()

parser.add_argument(
    '--supported_file_extensions',help='optional comma separated file extensions')
parser.add_argument(
    '--ignore_tests',action='store_true')
parser.add_argument(
    'input_dir',help='Fully qualified directory for the input directory')
parser.add_argument(
    'file_path',help='Fully  qualified path name for file')
parser.add_argument(
    'output',help='Fully qualified output directory path')
(arguments,extras) = parser.parse_known_args()
print(arguments)
print(extras)

致电:

python cloc.py --ignore_tests /myproject /myproject/.github/CODEOWNERS output.json --supported_file_extensions java,kt

optionals (--) 可以按任何顺序排列,但 positionals 必须按给定顺序排列。 positionals 没有标志或关键字。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 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元字符(。)和普通点?