Another solution is to always place the output of shlex.quote into unquoted context:
--action 'echo '{shlex.quote(text2)} # don't do this, see below
On a second thought, double-quoting as suggested by the first solution above is the way to go, since you’re passing text2 as the argument to a command which will be interpreted by another shell, so you would be vulnerable to injection attacks like text2='farewell; rm -rf /'. I.e., my “solution” here is analogous to passing an "echo $text2" command as the --action, while the double-quoting solution above is analogous to passing "echo $(printf '%q' "$text2")" as the --action:
Classic of me to disappear somewhere for months.
Yes, thank you, this is the way to go. Even the suggestion to add escape-style quoting as an alternative isn’t gonna make it since there is no way to quote zero-length string. Should’ve thought out it a little more to not have missed an obvious trivial case.