Editing Python scripts with Python
I'm开发者_运维知识库 trying to permanently edit variables within a Python script' source.
e.g.
urlpatterns = patterns('core.views',
)
to
urlpatterns = patterns('core.views',
url(r'^admin/', include(admin.site.urls)),
)
e.g.
items = [
'unicorn',
'cats',
]
to
items = [
'unicorn',
'cats',
'knights',
'panthers',
]
The problem is capturing the single variable, extending it and replacing it, source of the python file can be quite big and varied.
This has probably been done already, but cannot seem to find much around.
Any ideas, tips or suggestions?
My solution for now:
I'm just going to add code at the bottom of the script file
e.g.
urlpatterns += patterns('core.views',
url(r'^admin/', include(admin.site.urls)),
)
works for now :)
Python source code is, for this matter, a text file, so you pretty much open it and read/write data the usual way. I don’t think this is an amazingly good idea, but if you’re writing an installer of some sort...
If you're generating from a template, you could use plain old string formatting:
tmpl = """import foo
bar = 12345
myList = [
1,
2,
%s
]
otherStuff = %s"""
# figure out the values that need to go there
with f = open(filename, 'w+'):
f.write(tmpl % (item1, item2))
(Alternately instead of hard-coding that string, you could read it in from a file as well)
Or you could use one of the many templating engines for Python.
精彩评论