Question

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:

  1. Edit the configuration of Python apps that use source modules for configuration.

  2. 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.

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?

Was it helpful?

Solution

Python's standard library provides pretty good facilities for working with Python source; note the tokenize and parser modules.

OTHER TIPS

Most of these kinds of things can be determined programatically in Python, using modules like sys, os, and the special _file_ identifier which tells you where you are in the filesystem path.

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.).

There's a lot of power in this feature and something along these lines is probably what you're looking for. :)

[Edit] I've also used socket.gethostname() in some rare, hackish instances. ;)

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.

Otherwise AFAIK you have to use some conf objects.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top