简体   繁体   English

使用Python编辑Python脚本

[英]Editing Python scripts with Python

I'm trying to permanently edit variables within a Python script' source. 我正在尝试永久编辑Python脚本源中的变量。


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. 问题是捕获单个变量,扩展它并替换它,python文件的来源可能非常大且多变。

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. 对于这个问题,Python源代码是一个文本文件,所以你几乎可以打开它并以通常的方式读/写数据。 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 . 或者您可以使用Python的许多模板引擎之一

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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