0
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)
我懷疑它與美元符號和結構模塊有關,但我無法弄清楚。任何人都有線索?