【问题标题】:String replace in ubuntu python not workingubuntu python中的字符串替换不起作用
【发布时间】:2017-09-02 08:11:49
【问题描述】:
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)

我有这个文件,我将其用作在部署期间替换字符串的过程。它的执行是通过结构脚本远程完成的。

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 env 并重复完全相同的步骤,但它可以在 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)

我怀疑它与美元符号和结构模块有关,但我无法准确弄清楚。谁有线索?

【问题讨论】:

    标签: python python-2.7 ubuntu ubuntu-14.04 fabric


    【解决方案1】:

    这是fabric执行命令的方式 例如/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')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-08
      • 2016-02-15
      • 2016-10-05
      相关资源
      最近更新 更多