I have a python script which takes in command line arguments as input for processing and I'm using argparse
module for that.
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 -
. 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.
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:
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.