简体   繁体   中英

Editing Python scripts with Python

I'm trying to permanently edit variables within a Python script' source.


eg

urlpatterns = patterns('core.views',
)

to

urlpatterns = patterns('core.views',
    url(r'^admin/', include(admin.site.urls)),
)

eg

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

eg

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM