How to escape os.system() calls? How to escape os.system() calls? python python

How to escape os.system() calls?


shlex.quote() does what you want since python 3.

(Use pipes.quote to support both python 2 and python 3)


This is what I use:

def shellquote(s):    return "'" + s.replace("'", "'\\''") + "'"

The shell will always accept a quoted filename and remove the surrounding quotes before passing it to the program in question. Notably, this avoids problems with filenames that contain spaces or any other kind of nasty shell metacharacter.

Update: If you are using Python 3.3 or later, use shlex.quote instead of rolling your own.


Perhaps you have a specific reason for using os.system(). But if not you should probably be using the subprocess module. You can specify the pipes directly and avoid using the shell.

The following is from PEP324:

Replacing shell pipe line-------------------------output=`dmesg | grep hda`==>p1 = Popen(["dmesg"], stdout=PIPE)p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)output = p2.communicate()[0]