<p>This is something that I think would be very useful.  Basically, I'd like there to be a way to edit Python source programmatically without requiring human intervention.  There are a couple of things I would like to do with this:</p>

<ol>
<li><p>Edit the configuration of Python apps that use source modules for configuration.</p></li>
<li><p>Set up a "template" so that I can customize a Python source file on the fly.  This way, I can set up a "project" system on an open source app I'm working on and allow certain files to be customized.</p></li>
</ol>

<p>I could probably write something that can do this myself, but I can see that opening up a lot of "devil's in the details" type issues.  Are there any ways to do this currently, or am I just going to have to bite the bullet and implement it myself?</p>

[{'answer_id': 32402, 'author': 'Carl Meyer', 'author_id': 3207, 'author_profile': 'https://Stackoverflow.com/users/3207', 'pm_score': 4, 'selected': True, 'text': '<p>Python\'s standard library provides pretty good facilities for working with Python source; note the <a href="https://docs.python.org/2/library/tokenize.html" rel="nofollow noreferrer">tokenize</a> and <a href="https://docs.python.org/2/library/parser.html" rel="nofollow noreferrer">parser</a> modules.</p>\n'}, {'answer_id': 33325, 'author': 'Nico', 'author_id': 3504, 'author_profile': 'https://Stackoverflow.com/users/3504', 'pm_score': 0, 'selected': False, 'text': '<p>I had the same issue and I simply opened the file and did some replace: then reload the file in the Python interpreter. This works fine and is easy to do. </p>\n\n<p>Otherwise AFAIK you have to use some conf objects.</p>\n'}, {'answer_id': 35786, 'author': 'cdleary', 'author_id': 3594, 'author_profile': 'https://Stackoverflow.com/users/3594', 'pm_score': 0, 'selected': False, 'text': '<p>Most of these kinds of things can be determined programatically in Python, using modules like sys, os, and the special <a href="http://pyref.infogami.com/__file__" rel="nofollow noreferrer">_file_</a> identifier which tells you where you are in the filesystem path.</p>\n\n<p>It\'s important to keep in mind that when a module is first imported it will execute everything in the file-scope, which is important for developing system-dependent behaviors. For example, the os module basically determines what operating system you\'re using on import and then adjusts its implementation accordingly (by importing another module corresponding to Linux, OSX, Windows, etc.).</p>\n\n<p>There\'s a lot of power in this feature and something along these lines is probably what you\'re looking for. :)</p>\n\n<p>[Edit] I\'ve also used socket.gethostname() in some rare, hackish instances. ;)</p>\n'}]
['https://Stackoverflow.com/questions/32385', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2147/']