I just discovered that bash uses single quotes to preserve the literal value of a string (including spaces and stuff). The only problem with that is when your filename includes single quotes, but I found the workaround.
So here's some code with their results:
PHP Code:
import subprocess
# we need to pass shell as True to let bash interpret the single quotes as it normally would
subprocess.call("touch 'a new day.txt'", shell=True) # creates: a new day.txt
subprocess.call(r"touch 'a'\''new'\''day.txt'", shell=True) # creates: a'new'day.txt
Here's a function I wrote to automatically surrond with single quotes, replacing any single quotes with the appropriate string:
PHP Code:
#!/usr/bin/env python
import subprocess
def surround_with_single_quotes(string):
"""Surrounds the passed string with single quotes and replaces any
quotes with '\'' required by bash
>>> surround_with_single_quotes("a'new'day.txt")
"'a'\\\\''new'\\\\''day.txt'"
The previous example returns (without python's quotes and escape sequences):
'a'\''new'\''day.txt'
"""
str = string.replace("'", r"'\''")
str = "'" + str + "'"
return str
if __name__ == "__main__":
import doctest
doctest.testmod()
subprocess.call("touch " + surround_with_single_quotes("a'new'day.txt"), shell=True)
Bookmarks