简体   繁体   English

Python 命令行参数字符串以“-”开头

[英]Python Command Line Argument String starts with '-'

I have a python script which takes in command line arguments as input for processing and I'm using argparse module for that.我有一个 python 脚本,它接受命令行参数作为处理输入,我为此使用了argparse模块。

Relevant parsing code:相关解析代码:

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)

This file would run as (works fine):该文件将作为(工作正常)运行:

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

The issue is, some of my "pattern(s)" and "some_string(s)" start with - .问题是,我的一些“模式”和“some_string(s)”以-开头。 eg.例如。

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

This detects as issue in bash (shell I'm using to run the script, OS: Ubuntu 20.04) as it detects this as another argument rather than value of --pattern etc.这在 bash 中检测为问题(我用来运行脚本的 shell,操作系统:Ubuntu 20.04),因为它将此检测为另一个参数,而不是--pattern等的值。

How can I resolve this?我该如何解决这个问题?

EDIT: Added reading parsed args in the code and error I am getting编辑:在我得到的代码和错误中添加了读取解析的参数

As suggested by @Inian, I used the following way to run the script:按照@Inian 的建议,我使用以下方式运行脚本:

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

and instead of error, I got the expected output:而不是错误,我得到了预期的输出:

output.txt
-problem
-abc

And this solves my issue.这解决了我的问题。 Thanks.谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM