Converting an ugly path to a shell path

Nobody nobody at nowhere.com
Tue Sep 14 06:32:29 EDT 2010


On Tue, 14 Sep 2010 01:07:48 +0200, AmFreak wrote:

> 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.




More information about the Python-list mailing list