Why is this downvoted? What's the problem with this solution? It looks like the same kind of thing as Python's shlex.quote, which should work and about which the manual[1] says:
"The returned value is a string that can safely be used as one token in a shell command line, for cases where you cannot use a list."
[1] https://docs.python.org/3/library/shlex.html#shlex.quote