【问题标题】:Python Command Line Argument String starts with '-'Python 命令行参数字符串以 '-' 开头
【发布时间】:2021-12-23 18:07:52
【问题描述】:

我有一个 python 脚本,它接受命令行参数作为处理的输入,我正在使用 argparse 模块。

相关解析代码:

import argparse
my_parser = argparse.ArgumentParser(description="Sample code for reference")
my_parser.add_argument("--output_file", action="store", type=str, required=True)
my_parser.add_argument("--pattern", action="store", type=str, required=True)
my_parser.add_argument("--some_string", action="store", type=str, required=True)

args = my_parser.parse_args()
print(args.output_file)
print(args.pattern)
print(args.some_string)

此文件将运行为(工作正常):

python3 file.py --output_file output.txt --pattern "abc etc" --some_string "some string"
output.txt
abc etc
some string

问题是,我的一些“pattern(s)”和“some_string(s)”以- 开头。例如。

python3 file.py --output_file output.txt --pattern "-problem" --some_string "-abc"
usage: file.py [-h] --output_file OUTPUT_FILE --pattern PATTERN --some_string SOME_STRING
file.py: error: argument --pattern: expected one argument

这在 bash(我用来运行脚本的 shell,操作系统:Ubuntu 20.04)中检测为问题,因为它检测到这是另一个参数,而不是 --pattern 等的值。

我该如何解决这个问题?

编辑:在代码中添加了读取解析的参数和我得到的错误

【问题讨论】:

  • 使用= 分配值--pattern="-problem" --some_string="-abc"
  • 我已经运行了你的两个命令没有任何问题,你能分享错误信息吗?
  • 请将 bash 部分添加到您的问题中。
  • @Inian 我尝试了您的解决方案,它奏效了。不知道我怎么错过了这么简单的调整。谢谢:)

标签: python-3.x bash command-line-arguments argparse


【解决方案1】:

按照@Inian 的建议,我使用以下方式运行脚本:

python3 file.py --output_file output.txt --pattern="-problem" --some_string="-abc"

我得到了预期的输出,而不是错误:

output.txt
-problem
-abc

这解决了我的问题。谢谢。

【讨论】:

    猜你喜欢
    • 2019-12-24
    • 1970-01-01
    • 2016-10-06
    • 1970-01-01
    • 2016-07-30
    • 1970-01-01
    • 1970-01-01
    • 2021-12-04
    • 2021-08-19
    相关资源
    最近更新 更多