Generate config file from template using Python search and replace.

Peter Otten __peter__ at web.de
Tue Dec 1 05:49:37 EST 2015


Mr Zaug wrote:

> On Monday, November 30, 2015 at 4:14:48 AM UTC-5, Peter Otten wrote:
>> Mr Zaug wrote:
>> 
>> > On Sunday, November 29, 2015 at 5:50:51 PM UTC-5, Peter Otten wrote:
>> >> Mr Zaug wrote:
>> >> 
>> >> > When I run this script on OS X El Capitan, I see,
>> >> >   
>> >> >   # permission sensitive cache
>> >> >   $include "_dispatcher_shared_auth-checker:
>> >> > 
>> >> > Was I supposed to incorporate it into the script I posted?
>> >> 
>> >> Are you referring to my post? I'm sorry, I can't make sense of your
>> >> question.
>> > 
>> > Yes. The snippet you posted went way over my head. When I ran it, it
>> > printed
>> > 
>> > # permission sensitive cache
>> >   $include "_dispatcher_shared_auth-checker:
>> 
>> It's hard to tell from that problem description what might have gone
>> wrong. However:
>> 
>> In your template file you have to enclose all words you want to replace
>> in braces ("you have foo options" becomes "you have {foo} options"), to
>> replace all literal { with {{ and all literal } with }}.
>> 
>> Did you do that?
> 
> Yup, I sure did. So here is my current script. The only remaining task now
> is figuring out how to write the contents to a new file.
> 
> #!/usr/bin/env python
> import os
> import sys
> 
> script, template_file = sys.argv
> print "Opening the template file..."
> 
> print "What is the serial number of the site?",
> nnn = raw_input()

[...]

> with open (template_file, "r") as a_string:
>     data=a_string.read().replace('{SERVER_NAME}',
>     server_name).replace('{BRAND}', brand).replace('{CONTENT_PATH}',
>     content_path).replace('{DAMPATH}', dampath).replace('{ENV}',
>     env).replace('{CACHE_DOCROOT}', cache_docroot)

If all other braces are properly escaped you can use format instead of 
replace:

     data = a_string.read().format(
         SERVER_NAME=server_name,
         BRAND=brand,
         CONTENT_PATH=content_path
         DAMPATH=dampath,
         ENV=env,
         CACHE_DOCROOT=cache_doc_root)






More information about the Python-list mailing list