【发布时间】: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