python字符串中有没有一个方法可以在输出字符串中为我自动转义字符

2024-06-28 11:14:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我现在遇到了一个问题。我有一个python脚本,它接受一个linux命令,向该命令添加参数,然后执行它。该命令是grepsed的组合。现在问题出在grep中,我不需要对字符串中的字符进行转义,如下所示。但是,当我执行sed并且需要使用相同的变量时,我需要确保在字符串中首先转义特殊变量字符。像下面的例子一样,我必须将变量oldpathnewpath重写为oldpath_sednewpath_sed。我的问题是,是否有一种方法可以让我重用当前的变量。有没有一个python方法可以为我转义特殊字符?你知道吗

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]

Tags: to方法字符串命令linux字符grepsed