In python3.8, I have this code:
import shlex
item = "ABC'DEF"
quoteditem = shlex.quote(item)
print(quoteditem)
This is the output:
'ABC'"'"'DEF'
It's difficult to discern the double and single quotes here on this web page, so this is a description of what is printed:
single-quote
ABC
single-quote
double-quote
single-quote
double-quote
single-quote
DEF
single-quote
This is, of course, a correct shell quoting, but it is not the only possible shell quoting, and it is overly complex.
Another possibility is simply this:
"ABC'DEF"
And here's a second possibility:
ABC\'DEF
I much prefer these simpler versions. I know how to write python code to convert the complicated version into one of these simpler forms, but I'm wondering if there might be an already existing python function which can perform this kind of simpler shell quoting.
Thank you in advance for any suggestions.
This is sort-of an answer. It doesn't provide "... an already existing
pythonfunction which can perform this kind of simpler shell quoting", as I requested, since it now seems like such a quoting function doesn't exist inpython. However, it does show how I coded a quoting mechanism that provides simpler output (forpython-3.6or above):For earlier versions of
pythonwhich don't support f-strings,formatcan be used instead of those f-strings.Here are some examples. The lefthand column shows the assignment statement of the
pythonStringvariable within thepythonprogram. The righthand column shows what will then appear on the terminal whenprint(shellquote(pythonString))is invoked from within thepythonprogram:This is not the only way that the shell quoting could be performed, but at least the output is simpler than what comes out of
shlex.quotein many cases.