Mikuro
Crotchety UI Nitpicker
For the past day I've been wringing my hands trying to figure out the best way to pass a string variable in Python as an argument to a shell command.
I can't just do this:
Because if my_var contains, let's say, "'Lala-la'; rm -rf /", then it would delete all my files. It's obviously not safe, so I need to sanitize the input. Fair enough.
AppleScript has a "quoted form of ..." method that's useful for this, but I can't find any equivalent in Python (or Perl, which I also considered for this project).
So, I have two questions:
1. Is there a standard way of doing this that I'm not aware of? Perhaps a shell command that operates on stdin?
2. If I need to write my own function, would it be as simple as replacing all instances of "\" with "\\", replacing all instances of "'" with "\'", and then wrapping the result in single-quotes? i.e.,
I don't see why that would be a problem, but....aren't those famous last words? 
In my Google searching on the topic I've found lots of people like me reinventing the wheel, but I haven't found any authoritative answer. A lot of the sample code I found doesn't even escape backslashes, or just uses string formatting (which as far as I can tell doesn't filter the input at all). Ack!
I can't just do this:
Code:
input, output, error = os.popen3("echo " + my_var)
AppleScript has a "quoted form of ..." method that's useful for this, but I can't find any equivalent in Python (or Perl, which I also considered for this project).
So, I have two questions:
1. Is there a standard way of doing this that I'm not aware of? Perhaps a shell command that operates on stdin?
2. If I need to write my own function, would it be as simple as replacing all instances of "\" with "\\", replacing all instances of "'" with "\'", and then wrapping the result in single-quotes? i.e.,
Code:
def sanitize_arg(arg):
return "'" + arg.replace('\\','\\\\').replace('\'','\\\'') + "'"

In my Google searching on the topic I've found lots of people like me reinventing the wheel, but I haven't found any authoritative answer. A lot of the sample code I found doesn't even escape backslashes, or just uses string formatting (which as far as I can tell doesn't filter the input at all). Ack!
Last edited: