Converting an ugly path to a shell path

A

AmFreak

Hi,

im using a QFileDialog to let the user select a path that is used later in
a command send to the shell like this:

retcode = Popen(command + " " + path, shell=True, stdout = PIPE, stderr =
PIPE)

The problem that occurs now is when the user selects an "ugly" path like
this /home/user/!" §$/.
The shell don't understand the special chars so i have to escape them with
"\" .
Is there a function that does this ?
If there isn't i would use a RegEx but I can't even seem to find a list
containing all special chars :/

Greetings

AmFreak
 
L

Lawrence D'Oliveiro

In message
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@theon:hack> ./escape_try '<gt>\ & # *'
\<gt\>\\\ \&\ #\ \*
 
N

Nobody

im using a QFileDialog to let the user select a path that is used later in
a command send to the shell like this:

retcode = Popen(command + " " + path, shell=True, stdout = PIPE, stderr =
PIPE)

The problem that occurs now is when the user selects an "ugly" path like
this /home/user/!" §$/.
The shell don't understand the special chars so i have to escape them with
"\" .

Is there some fundamental reason why you're using a shell? Most of the
time, you're better off executing the command directly, i.e.:

process = Popen([command, path], shell=False, ...)

If you must "unparse" the path for the benefit of the shell, the first
question is: *which* shell?

For a typical Bourne shell, quoting a string using:

qstring = r"'" + string.replace(r"'", r"'\''") + r"'"

should be reliable. This won't work for Windows, though; look at the
source code for the subprocess module for the (rather bizarre) quoting
rules used by Windows.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,147
Latest member
CarenSchni
Top