Converting an ugly path to a shell path

Lawrence D'Oliveiro ldo at geek-central.gen.new_zealand
Tue Sep 14 05:23:03 EDT 2010


In message
<mailman.705.1284419324.29448.python-list at python.org>, AmFreak at web.de wrote:

> The shell don't understand the special chars so i have to escape them with
> "\" .
> Is there a function that does this ?

You could get the shell (at least if it’s Bash) itself to do this. Try the 
following script:

    import sys
    import os
    import subprocess

    os.environ["ARG1"] = sys.argv[1]
    sys.stdout.write \
      (
        subprocess.Popen
          (
            args = "printf $'%q\\n' \"$ARG1\"",
            stdout = subprocess.PIPE,
            shell = True
          ).communicate()[0]
      )

Sample output:

    ldo at theon:hack> ./escape_try '<gt>\ & # *'
    \<gt\>\\\ \&\ #\ \*




More information about the Python-list mailing list