0

I'm trying to open a path to file with some application. The problem is that the path contains various control characters that make it difficult to open the file. The following code shows my last attempt which prefixes control characters with \ but it strangely opens the file many times (like in endless loop).

path = path.replace("'", "\\'")
path = path.replace("(", "\\(")
path = path.replace(")", "\\)")
try:
  os.system("%s %s 2>/dev/null &" % (appForExtension[extension], path))
except:
  print "not opened"

Do you know how to standardly open the file with os.system() call avoiding the problems with control characters?

xralf
  • 3,312
  • 45
  • 129
  • 200

1 Answers1

1

Instead of using os.system you could use the subprocess module, and avoid passing your command through the shell. This means you won't have to worry about escaping quotation marks or other shell metacharacters...and in general, you won't need to worry about the shell (mis-)interpreting parts of the path.

import subprocess
res = subprocess.call([appForExtension[extension], path])

The docs for subprocess.call say:

subprocess.call = call(*popenargs, **kwargs)
    Run command with arguments.  Wait for command to complete, then
    return the returncode attribute.

...which you'll note is remarkably similar to os.system, except that subprocess.call avoids using the shell by default.

Redirecting stderr is left as an exercise to the reader...

larsks
  • 277,717
  • 41
  • 399
  • 399
  • I used rather *os.system()* because I don't want to wait for completion of command, what's why I use *&* and I don't want to see error messages, that's why I use *2> /dev/null/* – xralf Apr 30 '12 at 14:43
  • ...and you can accomplish the same thing using the `subprocess` module. Take a look at the docs; I think you'll find it much more flexible. – larsks Apr 30 '12 at 14:55
  • When I will add an argument *stderr="/dev/null"* for redirecting standard error output the file won't open and in the documentation I can't see nothing about running in background. If you're sure in this, please fix my arguments to be correct. – xralf Apr 30 '12 at 17:20