2

I want to edit an Apache2 config file within a python script. I want to add or remove a domain name to the ServerAlias directive so the script needs to edit a specific file and search for a line that starts with "ServerAlias" and append or remove a specific domain name to that line.

I'm not sure how to do it, any hint at documentation would be appreciated, I am also considering using a subprocess to use some bash tools like sed.

Bastian
  • 5,625
  • 10
  • 44
  • 68
  • Why does it need to be Python? – David Z Dec 31 '11 at 07:41
  • Because it is part of a Django project so it would be nice to use the same language throughout the project. And because I like Python :) – Bastian Dec 31 '11 at 09:32
  • possible duplicate of [Search and replace a line in a file in Python](http://stackoverflow.com/questions/39086/search-and-replace-a-line-in-a-file-in-python) – joaquin Dec 31 '11 at 10:06

2 Answers2

1

you can use fileinput.input with inplace mode:

import fileinput

for line in fileinput.input("mifile", inplace=True):
    if line.startswith("ServerAlias"):
        line = doherewhatyouwant(line)
    print line,

from docs:

if the keyword argument inplace=True is passed to fileinput.input() or to the FileInput constructor, the file is moved to a backup file and standard output is directed to the input file (if a file of the same name as the backup file already exists, it will be replaced silently). This makes it possible to write a filter that rewrites its input file in place. If the backup parameter is given (typically as backup='.'), it specifies the extension for the backup file, and the backup file remains around; by default, the extension is '.bak' and it is deleted when the output file is closed. In-place filtering is disabled when standard input is read.

joaquin
  • 82,968
  • 29
  • 138
  • 152
0

Couple of tools you would need for your trade

  1. str.startswith
  2. str.join or just + (string concatination)
  3. readline to read a file sequentially
  4. Offcourse opening and closing a file
  5. write a file
Abhijit
  • 62,056
  • 18
  • 131
  • 204
  • In case someone doesnt follow the link and see it, xreadlines is deprecated. Also he might need str.split or even regex if he is appending to values on the line – jdi Dec 31 '11 at 07:46
  • @jdi, Thanks I have updated the post. And as long as one can do without regex one should opt for it. As the OP just wants to check if the line begins with a certain string and just append a string onto it, OP may not need regex. – Abhijit Dec 31 '11 at 07:59
  • It looks like I have all I need to elaborate a script, thanks. If anybody could provide a simple example of how the tools interact together that would be just perfect. – Bastian Dec 31 '11 at 09:51