Reputation: 620
I have a requirement where I have to pass arguments to python script in the exact order below. I cannot change how the script gets called.
py_script.py -W ' code=123 and fruits='Apple' '
-W
argument is string
within single quotes. The string inturn contains a single quotes(fruits='Apple'
)
I am using argparse
to deal with this
Code:
import argparse
parser = argparse.ArgumentParser(description="abc")
parser.add_argument('-W', '--filt', metavar='', help="Filter Condition", nargs='+')
args = parser.parse_args()
arg_str = ' '.join(args.filt)
print(args.arg_str)
Expected result:
code=123 and fruits='Apple'
Actual result:
code=123 and fruits=Apple
The code is stripping off the single quotes. How do i get the expected result?
Upvotes: 2
Views: 7402
Reputation: 11739
One solution is to use double quotes around the argument, like this:
python script.py -W " code=123 and fruits='Apple' "
It is not the argparser package that is stripping off the single quotes. It is Python's built-in sys.argv handling of the arguments, and/or the Python processor itself.
Python require escapes to handle the same type of quote (single or double), but you can nest raw quotes of the opposite type without an escape character. If this violates the rules for the requirement - then you likely need to use a different language or push-back on the requirements.
You can test this by directly viewing the sys.argv output.
sysargtest.py:
import sys
for arg in sys.argv:
print('"{}"'.format(arg))
If I feed in python sysargtest.py -W ' code=123 and fruits='Apple' '
the result is:
$ py sysargtest.py -W ' code=123 and fruits='Apple' '
"sysargtest.py"
"-W"
" code=123 and fruits=Apple "
with the single quotes stripped. One way to solve this is using double quotes instead of single on the command line, if that is not part of your requirement:
$ py sysargtest.py -W " code=123 and fruits='Apple' "
"sysargtest.py"
"-W"
" code=123 and fruits='Apple' "
With that change argparse will work on the original script:
$ py script.py -W " code=123 and fruits='Apple' "
[" code=123 and fruits='Apple' "]
Upvotes: 2