搜索并用python字符串内带有单引号的代码替换文件文本

时间:2018-09-10 18:33:01

标签: python django

最近两天我有一个问题。 我正在尝试搜索并用单引号替换文本文件的一部分,但我收到错误。日志:

    Traceback (most recent call last):
  File "./vhost.py", line 194, in <module>
    """.format(db_name=_db_name, db_user=_db_user,db_pass=_db_pass, db_host=_db_host)
KeyError: "\n        'default'"

我认为问题出在“默认””

代码:

if _create_database == "Y" or _create_database == "y":
    _backendmysql = """
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql', 
            'NAME': '{db_name}',
            'USER': '{db_user}',
            'PASSWORD': '{db_pass}',
            'HOST': '{db_host}',   # Or an IP Address that your DB is hosted on
            #'PORT': '3306',
        }
    }
    """.format(db_name=_db_name, db_user=_db_user,db_pass=_db_pass, db_host=_db_host)

    _backendsqlite = '''
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        }
    }
    '''

    try:
      with fileinput.FileInput(strSettingsPath, inplace=True, backup=None) as file:
          for line in file:
              print(line.replace(bytes(_backendsqlite, 'UTF-8'), bytes(_backendmysql, 'UTF-8') , end=''))
    except Exception as e:
      raise e
# -----------------------------------------------------------------

0 个答案:

没有答案