Home > Article > Backend Development > How can I safely escape filenames and arguments for os.system() calls in Python?
When utilizing os.system() to execute command-line commands, the need to escape filenames and arguments passed as parameters arises, particularly in operating systems such as bash. Here's an effective method to accomplish this:
Escape Function Using shlex.quote()
Python 3 offers a convenient escape function named shlex.quote(). This function effectively converts any string into a properly escaped version that can be safely utilized as an argument in os.system() calls.
<code class="python">import shlex os.system(shlex.quote("cat %s | grep something | sort > %s" % (in_filename, out_filename)))</code>
Escape Function for Python 2 and 3
If you require backward compatibility with Python 2, you can use the pipes.quote function instead of shlex.quote(). However, note that pipes has been deprecated in Python 3.10 and will be removed in Python 3.13.
<code class="python">import pipes os.system(pipes.quote("cat %s | grep something | sort > %s" % (in_filename, out_filename)))</code>
Additional Note on Security
While os.system() offers a straightforward method for executing commands, it's essential to be cognizant of security concerns. Exercise caution when accepting input from untrusted sources.
The above is the detailed content of How can I safely escape filenames and arguments for os.system() calls in Python?. For more information, please follow other related articles on the PHP Chinese website!