How to escape os.system() calls in Python?
<p>When using os.system() it's often necessary to escape filenames and other arguments passed as parameters to commands.  How can I do this?  Preferably something that would work on multiple operating systems/shells but in particular for bash.</p>

<p>I'm currently doing the following, but am sure there must be a library function for this, or at least a more elegant/robust/efficient option:</p>

<pre><code>def sh_escape(s):
   return s.replace("(","\\(").replace(")","\\)").replace(" ","\\ ")

os.system("cat %s | grep something | sort &gt; %s" 
          % (sh_escape(in_filename), 
             sh_escape(out_filename)))
</code></pre>

<p><em>Edit:</em> I've accepted the simple answer of using quotes, don't know why I didn't think of that; I guess because I came from Windows where ' and " behave a little differently.</p>

<p>Regarding security, I understand the concern, but, in this case, I'm interested in a quick and easy solution which os.system() provides, and the source of the strings is either not user-generated or at least entered by a trusted user (me).</p>

<p><a href="https://docs.python.org/3/library/shlex.html#shlex.quote"><code>shlex.quote()</code></a> does what you want since python 3.</p>

<p>(Use <a href="https://docs.python.org/2/library/pipes.html#pipes.quote"><code>pipes.quote</code></a> to support both python 2 and python 3)</p>
