I'm trying to process an input string in a Python script which is taken as a command line argument. This input might contain quotes as well (both single and double is possible) and I'm not able to provide it as input. I tried escaping it (with \), does not work.
Here are the details:
python3 code.py --foo="foo" //works
python3 code.py --foo='foo' //works
python3 code.py --foo='f"o"o' //works
python3 code.py --foo="fo'o'" //works
python3 code.py --foo="fo\"o" //does not work
python3 code.py --foo='fo\'o' //does not work
For my use case, there could also be a mixture of single or double quotes as well. Is there a workaround?
If it matters, here is the relevant code:
import argparse
parser = argparse.ArgumentParser(description="Demo")
parser.add_argument("--foo", required=True)
args = parser.parse_args()
print(args.foo)
Here is what happens when I try and run using input that "does not work":
$ python3 code.py --foo='v\'1'
> ^C
I get a "prompt", which I then exit by ctrl-C. Basically, \ does not escape the (middle) quote, and bash identifies my command as incomplete.
CodePudding user response:
In a unix shell, to easily figure out the exact string you need to send to any commandline argument, you can use Python's shlex.quote():
>>> import shlex
>>> arg = r'''"fo\"o"'''
>>> print(shlex.quote(arg))
'"fo\"o"'
Make sure you wrap the argument with r and triple quotes.
If you happen to have triple quotes in your string, you'll have to manually escape everything without using r.
