RadiantHex
RadiantHex

Reputation: 25547

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

Upvotes: 0

Views: 2221

Answers (2)

Daniel DiPaolo
Daniel DiPaolo

Reputation: 56390

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.

Upvotes: 1

ayanami
ayanami

Reputation: 1696

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

Upvotes: 1

Related Questions