I am currently running into a problem. I have a python script that takes a linux command , adds parameters to that command and then executes it. The command is a combination of grep
and sed
. Now the problem is in grep I do not need to escape the characters in my string as shown below. However when I do a sed and I need to use the same variable I need to make sure that the special variable characters are escaped first in the string. Like in the following example I have to rewrite the variable oldpath
and newpath
to oldpath_sed
and newpath_sed
. My question is if there is a way for me to reuse my current variables . Is there a python method that will escape special characters for me ?
oldpath = "/myfolder/subfolderA/"
newpath = "/myfolder/subfolderB/"
#Ill be using the following variables as a parameter to a linux sed commmand which requires me to escape characters
oldpath_sed = "\/myfolder\/subfolderA\/"
newpath_sed = "\/myfolder\/subfolderB\/"
command = "grep -rl {0} {1} | sudo xargs sed -i 's/{2}/{3}/g'"
newcommand = command.format(oldString,folderName,oldString_sed,newString_sed)
ps = subprocess.Popen(newcommand,shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
output = ps.communicate()[0]