Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape os.system() calls?

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.

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:

def sh_escape(s):    return s.replace("(","\\(").replace(")","\\)").replace(" ","\\ ")  os.system("cat %s | grep something | sort > %s"            % (sh_escape(in_filename),               sh_escape(out_filename))) 

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

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

like image 795
Tom Avatar asked Aug 30 '08 09:08

Tom


People also ask

What does OS system () return?

By calling os. system() you can execute a system command, but it does not return the output to Python. This will run a command on your system. On Linux and Mac the command pwd returns the current directory, but any command will do.

Does OS system return exit code?

os. system() returns some unix output, not the command output. So, if there is no error then exit code written as 0.

How do you escape a Python shell?

I recommend you exit the Python interpreter with Ctrl-D . This is the old ASCII code for end-of-file or end-of-transmission. Seems like this method doesn't work if the script ran into an error. Ctrl-Break works consistently in Windows.

What is OS system in Python?

The OS module in python provides functions for interacting with the operating system. OS, comes under Python's standard utility modules. This module provides a portable way of using operating system dependent functionality. os. system() method execute the command (a string) in a subshell.


1 Answers

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

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

like image 195
pixelbeat Avatar answered Oct 19 '22 05:10

pixelbeat