在Ubuntu的Python替换字符串不工作

问题描述:

def monkey_patch_string(file_name, old_string, new_string): 
    # Read in the file 
    with open(file_name, 'r') as f : 
     filedata = f.read() 

    # Replace the target string 
    filedata = filedata.replace(old_string, new_string) 

    # Write the file out again 
    with open(file_name, 'w') as f: 
     f.write(filedata) 

if __name__ == '__main__': 

    file_name = sys.argv[1] 
    old_string = sys.argv[2] 
    new_string = sys.argv[3] 
    monkey_patch_string(file_name, old_string, new_string) 

我有这个文件,我用它作为部署过程中替换字符串的过程。它的执行是通过结构脚本远程完成的。在Ubuntu的Python替换字符串不工作

old_string = '"{}"'.format('$CONFIG_DIR') 
new_string = '"{}"'.format('$CONFIG_DIR --logfile /var/www/' + domain_name + '/logs/transmission.log') 
run('python deployment/monkey_patch.py /etc/default/transmission-daemon '+ old_string + ' ' + new_string) 

但不是将旧字符串替换为新字符串,而是用一些新字符串的垃圾值替换整个文件。
我甚至将文件复制到我的Windows环境,并重复完全相同的步骤,它的工作原理,但在Ubuntu上。 所有的时间,我是root用户,无论如何它的文件写入的东西,所以它也没有权限问题。

我已经试过这个文件的一些其他的字符串和文件,它的工作原理。

old_string = 'debian-transmission' 
new_string = 'www-data' 
run('python deployment/monkey_patch.py /etc/init.d/transmission-daemon '+ old_string + ' ' + new_string) 

我怀疑它与美元符号和结构模块有关,但我无法弄清楚。任何人都有线索?

它的结构执行命令 例如/bin/bash -l -c "Your commands goes here"

引用命令空间中的字符串正在创建问题。基本上它是字符串引用问题。 使用管道解决它。

import pipes 
old_string = pipes.quote('$CONFIG_DIR') 
new_string = pipes.quote('$CONFIG_DIR --logfile /var/www/' + domain_name + '/logs/transmission.log')